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
Post a Comment