将Controller的$ scope变量传递给嵌套指令的控制器

时间:2017-02-03 18:17:36

标签: angularjs data-binding angularjs-directive angularjs-scope angular-controller

我无法将范围对象从一个控制器传递到嵌套指令的控制器。 我在另一个指令(父)中有一个指令(子),父指令和它的控制器如下所示:

myApp.directive('parent', function(){
    return {
        restrict : 'E',
        scope:false,
        controller: 'parentController',
        templateUrl : '/templates/parent.html',
    };
});

myApp.controller('parentController', ['$scope',
function Controller($scope) {
    $scope.monitors=[monitor1,monitor2,monitor3]; //in reality these are JSON objects
}

我的'parent.html'模板如下所示:

<div>
    <!-- Other things go here -->
    <div ng-repeat='monitor in monitors'>
        <child monitorData='monitor'></child>
    </div>
</div>

child指令及其控制器如下所示:

myApp.directive('child', function(){
    return {
        restrict : 'E',
        scope:{
            monitorData:'=',
        },
        bindToController:true,
        controller: 'childController',
        templateUrl : '/templates/child.html',
    };
});

myApp.controller('childController', ['$scope', function ChildController($scope) {
    var vm=this;

    console.log('instantiated childController');
    console.log(vm);
}]);

控制台输出是:

instantiated childController
ChildController
    monitorData : undefined

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用monitorData的监视器数据。

<div>
<!-- Other things go here -->
<div ng-repeat='monitor in monitors'>
    <child monitor-Data='monitor'></child>
</div>

  

来自angular documentacion:注意:这些=范围内的attr属性   指令选项与指令名称一样被规范化。绑定   到&lt;中的属性div bind-to-this =“thing”&gt;,你要指定一个   绑定= bindToThis。

https://docs.angularjs.org/guide/directive

相关问题