AngularJS Tutorial - Directive-to-Directive Communication








The following code shows how to do directive-to-Directive Communication.

Example


<!doctype html>
<html ng-app="MyApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script>
var app = angular.module("MyApp", []);
<!--from   w  ww  .  j  ava2  s  . co m-->
app.directive("yourtag", function() {
  return {
    restrict: "E",
    controller: function($scope, $element, $attrs) {
      $scope.content = [];

      this.addA = function() {
        $scope.content.push("a");
      };

      this.addB = function() {
        $scope.content.push("b");
      };
    },
    link: function(scope, element) {
      element.bind("mouseenter", function() {
        console.log(scope.content);
      });
    }
  };
});

app.directive("a", function() {
  return {
    require: "yourtag",
    link: function(scope, element, attrs, myTagContr) {
      myTagContr.addA();
    }
  };
});

app.directive("b", function() {
  return {
    require: "yourtag",
    link: function(scope, element, attrs, myTagContr) {
      myTagContr.addB();
    }
  };
});    
    </script>
  </head>
  <body ng-app="MyApp">
    <yourtag a b>Roll over me and check the console!</yourtag>
  </body>
</html>

The code above is rendered as follows: