Freewind
Freewind

Reputation: 198188

How do directives communicate by a controller?

In this document: http://docs.angularjs.org/guide/directive, it says directives may communicate with each other by controllers.

controller - Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives if they request it by name (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.

I don't understand it well, how they communicated with controllers? Is there any example or demo for it?

Upvotes: 18

Views: 6665

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22933

Perhaps you're confusing a controller that is created when a route change occur with a directive controller. That section is only talking about directive controllers, so what that section means is that if you have two directives on the same HTML element, they can communicate by requiring each others controllers.

A good example of that is if your creating a directive that needs to communicate with ng-model. Since ng-model exposes a controller, you can require it like this:

myApp.directive('myDirective', function() {
    return {
        require: 'ngModel',
        link: function($scope, elem, attrs, ngModelCtrl) {
            // Here you can listen to different DOM events, and
            // call ngModelCtrl when the model value needs to update
        }
    }
});

And the HTML:

<input type="text" ng-model="myModel" my-directive>

Your directive can expose a controller by implementing it in the object that your directive function returns, like this:

myApp.directive('myDirective1', function() {
    return {
        link: function($scope, elem, attrs) {

        },
        controller: function() {
            this.sayHello = function() {
                alert("hello!");
            }
        }
    }
});

myApp.directive('myDirective2', function() {
    return {
        require: 'myDirective1',
        link: function($scope, elem, attrs, myDirective1Ctrl) {
            myDirective1Ctrl.sayHello();
        }
    }
});

And the HTML:

<input type="text" my-directive2 my-directive1>

You can also require a directive controller from a parent directive by writing require: '^myParentDirective', like this:

myApp.directive('myDirective1', function() {
    return {
        link: function($scope, elem, attrs) {

        },
        controller: function() {
            this.sayHello = function() {
                alert("hello!");
            }
        }
    }
});

myApp.directive('myDirective2', function() {
    return {
        require: '^myDirective1',
        link: function($scope, elem, attrs, myDirective1Ctrl) {
            myDirective1Ctrl.sayHello();
        }
    }
});

And the HTML:

<div my-directive1>
    <div my-directive2></div>
</div>

Upvotes: 34

Related Questions