【发布时间】:2018-12-20 19:19:05
【问题描述】:
假设我有几个控制器,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.
有什么方法可以处理或绕过这个错误?
【问题讨论】:
-
你可以有一个指令makes dynamic controllers