我尝试了一些类似Fiddle
的代码我需要在代码中的{{sp.peType}}
中动态传递参数controller-name
。
<div ng-repeat="sp in obj.PEs">{{sp.peType}}
<div add-icons controller-name="{{sp.peType}}"></div>
</div>
我的脚本代码就像
angular.module('myApp',[])
.controller("testCtrl", function($scope){
$scope.obj = {
"PEs": {
"1": {
"peId": "1",
"peName": "Exp1",
"peDisplayName": "Exp",
"peType": "Exp",
"peCategory": "PE"
},
"2": {
"peId": "2",
"peName": "RN1",
"peDisplayName": "RNull",
"peType": "RN",
"peCategory": "PE"
}
}
}
})
.directive('addIcons', function(){
return {
restrict : 'A',
scope:{},
controller : "@",
name:"controllerName"
}
}).
controller("Exp",function($scope){
alert("Exp Contorller")
}).
controller("RN",function($scope){
alert("RN controller");
});
但这似乎不起作用!
获取此错误
错误:[ng:areq]参数&#39; {{sp.peType}}&#39;得到了,不是一个功能 未定义
任何想法都是赞赏的!
答案 0 :(得分:0)
这是因为PEs
是一个对象,而不是一个数组。将PEs
更改为:
"PEs": [
{
"peId": "1",
"peName": "Exp1",
"peDisplayName": "Exp",
"peType": "Exp",
"peCategory": "PE"
},
{
"peId": "2",
"peName": "RN1",
"peDisplayName": "RNull",
"peType": "RN",
"peCategory": "PE"
}
]
答案 1 :(得分:0)
我做了this fiddle
为什么没有指令控制器并将控制器名称作为指令参数传递并在指令控制器内部执行整个逻辑?
HTML
<div add-icons controller-name="sp.peType"></div>
指令
.directive('addIcons', function() {
return {
restrict: 'A',
scope: {
'controllerName': '='
},
controller: function($scope) {
console.log($scope.controllerName);
switch ($scope.controllerName) {
case 'Exp':
expControllerLogic();
break;
case 'RN':
rnControllerLogic();
break;
default:
alert("Default");
}
function expControllerLogic() {
alert('Exp Controller');
}
function rnControllerLogic() {
alert("RN controller");
}
}
}
});