angularjs什么时候渲染model变量?

我有这样一个需求:ChartController会生成变量,将数值赋给div的id,然后GraphController中用到div的id变量,但是GraphController中的方法需要div的id已被渲染才行。

<div ng-controller="ChartController">
  <div ng-repeat="id in chart.id">
    <div id="{{ id.value }}" ng-controller="GraphController"><div>
  <div>
</div>

如果GraphController的xx方法被调用的时候,我查看前端的代码,div的id名称还是

<div id="{{ id.value }}"...

去除ng-controller="GraphController"后,发现div的id渲染正确

<div id="abc123"...

很奇怪!

阅读 7.1k
3 个回答

我不建议将angular的模板语言直接放在id或者class这些属性里,可以用ng-class,ng-href,ng-src这些属性代替。

angular里的controller不是类,不能用类似楼主那样的方法直接从一个controller里新建多个类并传值给它们。

楼主需要的是directive

<div ng-controller="ChartController">
  <div ng-repeat="id in chart.id">
    <graph graph-id="id.value"></graph>
  <div>
</div>
app.directive("graph",function(){
    return {
        template: '<div>{{id}}</div>',
        scope:{
            //注意这里
            //如果是'@graphId'的话,则返回的是字符串"id.value"
            //graphId对应的html属性为"graph-id"
            id:'=graphId'
        },
        restrict:'E',
        controller:function($scope){
            console.log($scope.id);
            //abc123

            //将GraphController的代码放在这里
        }
    }
})

http://plnkr.co/edit/M1gtlySErXvSOgQayxF6?p=preview

关于directive,看这里

ng-controller会开个新的scope

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题