通常,我想要做的是使用变量初始化 ng-repeat
内嵌套的 ng-controller
。
JS
angular.module('app',[])
.controller('main',function($scope){
angular.extend($scope,{
name:'Parent Controller',
items:[
{name:'nested2'},
{name:'nested1'}
]
});
})
.controller('nested1',function($scope){
$scope.name = "Name1";
})
.controller('nested2',function($scope){
$scope.name = "Name2";
});
我想要这个:
<div ng-controller="main" ng-app='app'>
Nested: {{name}}
<div ng-controller="nested1">{{name}}</div>
<div ng-controller="nested2">{{name}}</div>
</div>
变成这样:
<div ng-controller="main">
Nested: {{name}}
<div ng-repeat="item in items">
<div ng-controller="item.name">{{name}}</div>
</div>
</div>
问题:这样不行。它也没有任何其他方式工作,我在谷歌搜索一个小时左右后尝试过。
是否有任何“合法”且好的方法来实现这一目标?
最佳答案
我想,目前还没有真正的方法可以使用 Angular 特征。您可以创建一个指令并使用未记录的动态 Controller 功能controller:'@', name:'controllerName'
。但这种方法不会评估提供 Controller 名称的绑定(bind)或表达式。我能想到的是通过实例化提供的 Controller 并将其设置为元素来进行黑客攻击。
示例:-
.directive('dynController', function($controller){
return {
scope:true, //create a child scope
link:function(scope, elm, attrs){
var ctrl =scope.$eval(attrs.dynController); //Get the controller
///Instantiate and set the scope
$controller(ctrl, {$scope:scope})
//Or you could so this well
//elm.data('$ngControllerController', $controller(ctrl, {$scope:scope}) );
}
}
});
在你看来:-
<div ng-controller="main">
<div ng-repeat="item in items">
Nested:
<div dyn-controller="item.name" ng-click="test()">{{name}}</div>
</div>
</div>
<强> Demo
请注意,我已经从执行 ng-repeat 的元素更改了 ng-controller 的位置,因为 ng-repeat (1000
) 的优先级高于 ng-controller (500
),ng-repeat 的范围将占上风,你最终不会重复任何东西。
看着的时候
关于javascript - AngularJS,变量的嵌套 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219866/