Parametrise控制器可以在不同的指令中工作(Parametrise controller to work in different directives)
我需要在angularJS中使用几个不同的指令。 指令具有不同的模板,控制器应以非常相似的方式工作,彼此之间的变化非常小。
我想只使用一个共享控制器,使其行为适应它所包含的指令,如代码中描述的想法:
var module = angular.module('app', []); module.directive('myFirstDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/first.html' }; }); module.directive('mySecondDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/second.html' }; }); module.controller('MyController', function ($scope) { $scope.myEvent = function () { //if it's first directive do this //if it's second directive do that }; });这有什么办法吗?
I need to work with several different directives in angularJS. The directives have different templates and the controllers should work in very similar way, with very small changes each-other.
I was thinking to use just one shared controller that adapt its behaviour to the directive it's included like the idea described in code:
var module = angular.module('app', []); module.directive('myFirstDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/first.html' }; }); module.directive('mySecondDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/second.html' }; }); module.controller('MyController', function ($scope) { $scope.myEvent = function () { //if it's first directive do this //if it's second directive do that }; });Is there any way in angular to do this?
最满意答案
您可以在指令中使用ng-init="callback1()"和ng-init="callback2()" 。 并描述控制器中的两个回调。
You can use ng-init="callback1()" and ng-init="callback2()" in your directives. And describe both callbacks in your controller.
更多推荐
发布评论