How to get AngularJS Directive name from inside Controller Code? -


i have 2 angularjs directives similar, want use 1 single controller handle both of them. in order differentiate in controller code between 2 directives, want able know directive being used. there way can tell? sounds trivial function in angularjs, can't find in docs far.

<div dira ></div> <div dirb'></div>  app.directive('dira', function() {     return {         restrict: 'a',         replace: true,         controller: 'commonctrl',     }; });  app.directive('dirb', function() {     return {         restrict: 'a',         replace: true,         controller: 'commonctrl',     }; });  app.controller('commonctrl',     function commonctrl($scope, $location, $log, $attrs) {       // how know directive using me now???     } ); 

sure can set property on directive's controller, automatically injected linking function if specified:

here's plunk it

var app = angular.module('myapp', []);  app.directive('dira', function (){   return {     controller: 'commonctrl',     scope: true,     template: '<button ng-click="test()">test a</button>',     link: function(scope, elem, attrs, ctrl) {       ctrl.directivename = 'dira';     }   }; });  app.directive('dirb', function (){   return {     controller: 'commonctrl',     scope: true,     template: '<button ng-click="test()">test b</button>',     link: function(scope, elem, attrs, ctrl) {       ctrl.directivename = 'dirb';     }   }; });  app.controller('commonctrl', function ($scope, $window){   var ctrl = this;    $scope.foo = 'bar';    $scope.test = function (){     $window.alert('directive name is: ' + ctrl.directivename);   }; }); 

this not idea, though.

coupling warning!

this going lead tighter coupling in app. because have dependency between controller supposed encapsulate logic manipulates $scope (model), , view because controller has reference directive name or directive-specific data @ least. going hurt testability , possibly readability in long run.

suggestion: use inheritence

if case have different functionality different directives, it's better practice create commonctrl, create diractrl , dirbctrl prototypically inherit commonctrl... if makes sense.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -