让我们假设我有几个控制器controller1
,controller2
等,它们都采用相似的数据,但执行的任务却截然不同。这样的控制器的一个例子是:
angular.module('myApp').controller('controller1', ['$scope', function($scope) {
$scope.limit = undefined;
$scope.answer = undefined;
$scope.hasresult = false;
$scope.run = function() {
// Do some controller-specific stuff here...
}
}]);
所有其他控制器将实例化limit
,answer
,hasresult
和run
。这可以让我做这样的事情:
angular.module('myApp').controller('controller_indexer', ['$scope', function($scope) {
$scope.controllers =
[
{
index: 1,
name: 'Some special name',
result: 'Some results from {{limit}} --> {{answer}} here'
}
];
}]);
现在,在我的HTML文件中,我想做的是这样:
<div ng-app="myApp" ng-controller="controller_indexer">
<div ng-repeat="x in controllers">
<div ng-controller="controller{{x.index}}">
<!-- do some stuff here -->
</div>
</div>
</div>
但是,这种方法会导致类似以下错误:
The controller with the name 'controller{{x.index}}' is not registered.
有什么办法可以解决这个错误或解决它?
答案 0 :(得分:1)
发现here
mainApp.directive('ngDynamicController', ['$compile', '$parse',function($compile, $parse) {
return {
scope: {
name: '=ngDynamicController'
},
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem, attrs) {
elem.attr('ng-controller', scope.name);
elem.removeAttr('ng-dynamic-controller');
$compile(elem)(scope);
}
};
}]);
您可以像这样使用它:
<div class="col-xs6 col-sm-5 col-md-4 col-lg-3" ng-repeat="box in boxes">
<div ng-include src="'/assets/js/view/box_campaign.html'" ng-dynamic-controller="box.type"></div>
</div>