jthomasbailey
jthomasbailey

Reputation: 410

Angular directive to directive communication?

Actually all I need is somewhere to put a reusable function that has access to $scope.

Here's an attempt at a simplified example of what I'm trying to do: Plnkr

I'm still getting the hang of directives.

var app = angular.module('plunker', []);

app.directive('dir1', function() {
    return {
        restrict: 'AE',
        link: function(scope, element, attrs) {
            element.click(function() {
                scope.message = "Hey Now";
                scope.doSomething();
            });
        }
    };
});

app.directive('dir2', function() {
    return {
        restrict: 'AE',
        link: function(scope, elem, attr) {
            scope.doSomething = function() {
                alert($scope.message);
            }
        }
    };
});

and:

<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <dir1>click me</dir1>
</body>
</html>

Upvotes: 1

Views: 215

Answers (1)

vittore
vittore

Reputation: 17579

You can use require parameter of directive in order to communicate to another directive. Here is an example:

 var app = angular.module('plunker', []);

app.directive('dir1', function(){
return {
  restrict: 'AE',
  require:'dir2',
  link: function(scope, element, attrs, dir2) {

         element.bind('click', function() {

           dir2.message = "Hey Now";
           alert(JSON.stringify(dir2))
           dir2.doSomething();

         });

  }
};
});

app.directive('dir2', function(){
return {
  restrict: 'AE',
  controller : function ($scope) {
     this.doSomething = function(){
       alert(this.message);
     }

  }

};
});

Upvotes: 1

Related Questions