[英]Is there any way to assign ng-controller dynamically when iterate over an collection of objects?
使用角1.6.6和ui-bootstrap 2.5.0
每個選項卡的邏輯都非常不同,因此我不想將所有選項卡放在一個控制器中。 這個問題有什么辦法嗎?
操作
$scope.actions = [
{
slug: "basicData",
title: "Grunddata",
icon: "fa fa-table",
template: templatePath + "basicData.html",
disabled: false,
controller: null
}, {
slug: "responsible",
title: "Ansvariga",
icon: "fa fa-address-book-o",
template: templatePath + "responsible.html",
disabled: false,
controller: null
}, {
slug: "reportTime",
title: "Rapportera tid",
icon: "fa fa-clock-o",
template: templatePath + "reportTime.html",
disabled: false,
controller: "ActivityTimeReportingController"
}
]。
這是我的標簽
<uib-tabset active="activePill" vertical="true" type="pills">
<uib-tab ng-repeat="action in actions" index="$index+1" disable="action.disabled">
<uib-tab-heading>
<span class='{{action.icon}}'></span> {{action.title}}
</uib-tab-heading>
<div ng-include="action.template" ng-if="!action.controller" ng-controller="action.controller"></div>
<div ng-include="action.template" ng-if="action.controller"></div>
</uib-tab>
</uib-tabset>
我收到以下錯誤
名稱為“action.controller”的控制器未注冊。
卷曲括號沒有任何區別。
我嘗試過使用函數:
$scope.getController = function (controllerName) {
return controllerName.ToString();
};
在我的標簽中:
<div ng-include="action.template" ng-if="!action.controller" ng-controller="getController(action.controller)"></div>
使用相同的錯誤消息
名為'getController(action.controller')的控制器未注冊。
在迭代對象集合時,有沒有辦法動態分配ng-controller?
創建動態指令,然后為每個指定一個控制器,幾乎不使用ng-include roll你自己的動態指令和綁定模板url
http://www.codelord.net/2015/05/19/angularjs-dynamically-loading-directives/
如果您沒有太多類型的操作..然后使用ng-if或ng-switch並使用ng-controller或使用控制器的指令為每個操作創建一行。 您嘗試實現的動態代碼不是正確的方法,imo。
這是一個有效的解決方案: http : //jsfiddle.net/wt42nqLn/
HTML
<script type="text/ng-template" id="customControllerTemplate.html">
Controller name: {{name}}
</script>
<div ng-controller="myCtrl">
<div ng-repeat="controller in controllerList">
<div custom-controller="controller.name">
<div ng-include="'customControllerTemplate.html'"></div>
</div>
</div>
</div>
JS
var myApp = angular.module('myApp',[]);
myApp.controller('myCtrl', myCtrl);
myApp.controller('firstController', firstController);
myApp.controller('secondController', secondController);
myApp.directive('customController', customController);
function myCtrl($scope) {
$scope.controllerList = [
{
name: 'firstController'
},
{
name: 'secondController'
}
]
}
function firstController($scope){
console.log('firstController','loaded');
$scope.name = 'firstController';
}
function secondController($scope){
console.log('secondController','loaded');
$scope.name = 'secondController';
}
function customController($compile){
return {
priority:1001,
terminal:true,
link: function(scope,element,attrs){
var ctrlName = scope.$eval(attrs['customController']);
element = angular.element(element.children());
element.attr('ng-controller',ctrlName);
$compile(element)(scope);
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.