html - AngularJS - 如何引用具有非常量名称的控制器
问题描述
假设我有几个控制器、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.
有没有办法处理这个错误或绕过它?
解决方案
如发现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>
推荐阅读
- jenkins - Jenkins Cors 插件未启用 Access-Control-Allow-Header
- swift - 如何在情节提要中忽略/隐藏约束警告?
- arrays - setValues 是否比 setValue 慢?
- javascript - 使用服务器端容器从 Google 跟踪代码管理器调用脚本
- spring-boot - 原因:无法构造`org.springframework.security.core.userdetails.UserDetails`的实例(没有创建者,如默认构造函数,存在)
- python - 错误中未显示任何详细信息
- javascript - 在浏览器中访问 tabCapture (puppeteer)
- vba - 使用 VBA 的基于令牌的身份验证
- c# - 在 ControlTemplate 上覆盖 IsMouseOver 使 Button 消失
- xcuitest - 使用 Xcuitest 从电子邮件获取验证令牌