Is it possible to find out which directive initialized my controller

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 indicate which directive is initialized ExampleCtrlinside this controller?

+4
source share
2 answers

You can do it:

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 Nis equal to 1 or 2 or as much as you have, it will exist only if it came from a directive N. This is how the syntax works controllerAs, it just publishes in the field.

Something like that:

app.controller('ExampleCtrl', function($scope, $element) {
  if ($scope.dir1Ctrl) /* do something */
  if ($scope.dir2Ctrl) /* do something else */
});

Plunker

+1
source

I thought of two ways. I find this solution much less hacked, but 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";
    }
};});

, .


, . , :

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

, (, ). , , (, XY ), .

+1

Source: https://habr.com/ru/post/1584527/