Angular,如何在 ng-repeat 之前将控制器分配给标记
Angular, how to assign controller to markup before ng-repeat
谁能告诉我是否可以在 ng-repeat 执行他的操作之前将指令中的控制器分配给标记?
下面的代码只是我想做的一个例子
<body ng-app="App">
<div my-t>
<div ng-repeat="obj in List">
{{obj.Name}}
</div>
</div>
angular.module('App',[])
.directive('myT',[function(){
return {
replace : true,
transclude : true,
template : '<div ng-controller="listCtrl"><div ng-transclude></div></div>'
};
}])
.controller('listCtrl', ['$scope', function($scope){
$scope.List = [
{Name: 'a'},{Name: 'b'}
];
}]);
问题是,当我的指令更改模板时,分配给 ng-controller 的 ng-repeat 已经编译,因此它不会显示任何数据。将 ng-controller 移动到标记中不是一个选项。
最佳。
您还可以将控制器放入您的指令中,使用 controller: 'listCtrl'
,然后您还可以从模板中删除 ng-controller
。
<div my-t>
<div ng-repeat="obj in List">
{{obj.Name}}
</div>
</div>
控制器
angular.module('App',[])
.directive('myT',[function(){
return {
restrict: 'A',
replace : true,
transclude : true,
template : '<div><div ng-transclude></div></div>',
controller : 'listCtrl'
};
}])
.controller('listCtrl', ['$scope', function($scope){
$scope.List = [
{Name: 'a'},{Name: 'b'}
];
}]);
谁能告诉我是否可以在 ng-repeat 执行他的操作之前将指令中的控制器分配给标记?
下面的代码只是我想做的一个例子
<body ng-app="App">
<div my-t>
<div ng-repeat="obj in List">
{{obj.Name}}
</div>
</div>
angular.module('App',[])
.directive('myT',[function(){
return {
replace : true,
transclude : true,
template : '<div ng-controller="listCtrl"><div ng-transclude></div></div>'
};
}])
.controller('listCtrl', ['$scope', function($scope){
$scope.List = [
{Name: 'a'},{Name: 'b'}
];
}]);
问题是,当我的指令更改模板时,分配给 ng-controller 的 ng-repeat 已经编译,因此它不会显示任何数据。将 ng-controller 移动到标记中不是一个选项。
最佳。
您还可以将控制器放入您的指令中,使用 controller: 'listCtrl'
,然后您还可以从模板中删除 ng-controller
。
<div my-t>
<div ng-repeat="obj in List">
{{obj.Name}}
</div>
</div>
控制器
angular.module('App',[])
.directive('myT',[function(){
return {
restrict: 'A',
replace : true,
transclude : true,
template : '<div><div ng-transclude></div></div>',
controller : 'listCtrl'
};
}])
.controller('listCtrl', ['$scope', function($scope){
$scope.List = [
{Name: 'a'},{Name: 'b'}
];
}]);