Reputation: 197
Let's say I have two directives:
angular.module('example').directive('dir1', function () {
return {
restrict: 'A',
scope: true,
controller: 'ExampleCtrl'
};});
angular.module('example').directive('dir2', function () {
return {
restrict: 'A',
scope: true,
controller: 'ExampleCtrl'
};});
Is it possible to tell which directive initialized ExampleCtrl
inside this controller?
Upvotes: 4
Views: 122
Reputation: 7078
You can do this:
angular.module('example').directive('dir1', function () {
return {
restrict: 'A',
scope: true,
controller: 'ExampleCtrl',
controllerAs: 'dir1Ctrl'
};});
angular.module('example').directive('dir2', function () {
return {
restrict: 'A',
scope: true,
controller: 'ExampleCtrl',
controllerAs: 'dir2Ctrl'
};});
Then, in the controller, $scope.dirNcontroller
, where N
is 1 or 2 or as many as you have, will exist only if it came from directive N
. This is how the controllerAs
syntax works, it is simply published to the scope.
Something like this:
app.controller('ExampleCtrl', function($scope, $element) {
if ($scope.dir1Ctrl) /* do something */
if ($scope.dir2Ctrl) /* do something else */
});
Upvotes: 1
Reputation: 20129
I thought of 2 ways. This solution I find much less hacky, but is also less dynamic:
angular.module('example').directive('dir1', function () {
return {
restrict: 'A',
scope: true,
controller: 'ExampleCtrl',
link: function(scope) {
$scope.myDir="dir1";
}
};});
angular.module('example').directive('dir2', function () {
return {
restrict: 'A',
scope: true,
controller: 'ExampleCtrl'
link: function(scope) {
$scope.myDir="dir2";
}
};});
In this way you are baking the parent directive into the scope, which is available to the controller.
This solution is more hacky, but also more dynamic. Using this question, we can get our containing element:
function innerItem($scope, $element){
var jQueryInnerItem = $($element);
}
from there, we can test that element for attributes and properties that would be specific to one directive over another (such as directive name). I still think this is very hacky and you have an underlying issue (perhaps a bit of XY problem here), but this should work.
Upvotes: 1