谈话很便宜,首先显示我的代码:
HTML:
<div add-icons="IconsCtrl"> </div>
指示:
angular.module('attrDirective',[]).directive('addIcons',function($compile){ return { restrict : 'A',controller : "IconsCtrl" },link : function (scope,elem,attrs,ctrl) { var parentElem = $(elem); var icons = $compile("<i class='icon-plus' ng-click='add()'></i>)(scope); parentElem.find(".accordion-heading").append(icons); },}
});
控制器:
function IconsCtrl($scope){ $scope.add = function(){ console.log("add"); }; }
但我想把控制器设置为指令动态,像这样:
HTML:
<div add-icons="IconsOneCtrl"> </div> <div add-icons="IconsTwoCtrl"> </div>
控制器:
function IconsOneCtrl($scope){ $scope.add = function(){ console.log("IconsOne add"); }; } function IconsTwoCtrl($scope){ $scope.add = function(){ console.log("IconsTwo add"); } }
指令喜欢:
angular.module('attrDirective',controller : dynamic set,depends on attrs.addIcons },} });
如何实现我的目标?感谢您的回答!
现在可以用AngularJS。在指令中,您只需添加两个新的属性
控制器,名称属性和隔离范围在这里是完全需要的。
原文链接:https://www.f2er.com/angularjs/145405.html控制器,名称属性和隔离范围在这里是完全需要的。
重要注意在指令
scope:{},//isolate scope controller : "@",// @ symbol name:"controllerName",// controller names property points to controller.
Working Demo for Setting Dynamic controller for Directives
HTML标记:
<communicator controller-name="PhoneCtrl" ></communicator> <communicator controller-name="LandlineCtrl" ></communicator>
角度控制器和指令:
var app = angular.module('myApp',[]). directive('communicator',function(){ return { restrict : 'E',scope:{},controller : "@",name:"controllerName",template:"<input type='text' ng-model='message'/><input type='button' value='Send Message' ng-click='sendMsg()'><br/>" } }). controller("PhoneCtrl",function($scope){ $scope.sendMsg = function(){ alert( $scope.message + " : sending message via Phone Ctrl"); } }). controller("LandlineCtrl",function($scope){ $scope.sendMsg = function(){ alert( $scope.message + " : sending message via Land Line Ctrl "); } })
您的案例,您可以尝试以下代码片段。
HTML标记:
<div add-icons controller-name="IconsOneCtrl"> </div> <div add-icons controller-name="IconsTwoCtrl"> </div>
角码:
angular.module('myApp',[]). directive('addIcons',function(){ return { restrict : 'A',template:'<input type="button" value="(+) plus" ng-click="add()">' } }). controller("IconsOneCtrl",function($scope){ $scope.add = function(){ alert("IconsOne add "); } }). controller("IconsTwoCtrl",function($scope){ $scope.add = function(){ alert("IconsTwo add "); } });