AngularJS: how to target a specific directive with multiple instances

I have several instances of the directive, and I would like to target only a specific instance. For example, in the code below, how can I make sure div c class="one"is the only one that is triggered by the event $rootScope.$broadcast('myEvent').

JS:

myApp.directive('myDirective', function() {
    return {
        restrict: 'A',
        controller: function(scope, el, attrs) {
            scope.$on('myEvent', function() {
                el.css({left: '+=100'});
            });
        },
    };    
});

HTML:

<div my-directive class="one"></div>
<div my-directive class="two"></div>
+5
source share
3 answers

You must do this check in the event handler:

myApp.directive('myDirective', function() {
  return {
    restrict: 'A',
      controller: function(scope, el, attrs) {
        scope.$on('myEvent', function(ev,args) {
          //do the check - you could provide a function, a value or something else
          if(el.hasClass(args.class)){
            el.css({left: '+=100'});
          }
        });
      },
  };    
});

Then add the parameters to $ broadcast

$rootScope.$broadcast('myEvent',{class:'one'})
+4
source

You can define a new attribute for this directive that refers to a callback that is then executed inside the $ on callback:

myApp.directive('myDirective', function() {
    return {
        restrict: 'A',
        scope: {
          callme: "="
        },
        controller: function(scope, el, attrs) {
            scope.$on('myEvent', function() {
                scope.callme(el)
            });
        },
    };    
});

HTML declaration:

<div my-directive class="one" callme="functionDefinedInScope"></div>

In the area of ​​your controller:

$scope.functionDefinedInScope = function(el) {
    el.css({left: '+=100'});
}

: http://docs.angularjs.org/guide/directive ( " " )

+1

You can use id instead of class

<div my-directive id="one"></div>
<div my-directive id="two"></div>

and in your controller

controller: function(scope, el, attrs) {
   scope.moveElement = function() {
      el.css({left: '+=100'});
   }
}

and then instead of broadcasting

angular.element('#one').scope().moveElement()
0
source

All Articles