Directive-to-directive communication in AngularJS? -


i know can set controller within directive, , other directives can call functions on controller. here's current directive looks like:

app.directive("foobar", function() {   return {     restrict: "a",     controller: function($scope) {       $scope.trigger = function() {         // stuff       };     },     link: function(scope, element) {      // more stuff     }   }; }); 

i know call this:

app.directive("bazqux", function() {   return {     restrict: "a",     require: "foobar",     link: function(scope, element, attrs, foobarctrl) {         foobarctrl.trigger();     }   }; }); 

however, want able call trigger any directive, not own custom ones, this:

<button ng-click="foobar.trigger()">click me!</button> 

if doesn't work, there way bring in third directive make happen? this?

<button ng-click="trigger()" target-directive="foobar">click me!</button> 

thanks!

one simple way of accomplishing application-wide communication between components use global events (emitted $rootscope). example:

js:

app.directive('directivea', function($rootscope) {     return function(scope, element, attrs)     {         // can attach event listeners in place (controllers, too)          $rootscope.$on('someevent', function()         {             alert('directive responds global event');         });     }; }); 

html:

<button ng-click="$emit('someevent')">click me!</button> 

here you're emitting event child scope reach $rootscope , run previous listener.

here's live example: http://plnkr.co/edit/cpktr5r357tep32lojug?p=preview


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -