How to use a controller for two directives?

I have this code:

JS:

angular.module("module") .controller("fooController", ["$scope", function($scope) { ... }) .directive("foo", function() { return { restrict: "E", controller: "fooController", link: function($scope, $element, $attrs) { // Do some things with the scope of the controller here } } }) .directive("bar", function() { return { restrict: "E", require: "fooController", link: function($scope, $element, $attrs) { // Nothing yet } } }); 

HTML:

 <html> <head> <!-- Scripts here --> </head> <body ng-app="module"> <foo/> <bar/> </body> </html> 

The foo directive works, but the bar directive throws an error: No controller: fooController .

How can I fix this by preserving the current structure (the controller is not inside HTML, but used by directives, bar is outside foo and uses the same controller, and both change its scope)? I read the discussion here , but I could not figure out how to do this.

+8
angularjs
source share
2 answers

Since your ultimate goal is to establish communication between the controllers, you do not need to reuse the same controller under several directives (I doubt that reusing will allow you to communicate). In any case, the best way to do this is to use the services.

Article Can one controller call another? talks about this in detail, but in simple words, first create a service:

 app.factory('myService', function () { var data; return { getData: function () { return data }, setData: function (newData) { data = newData; } }; }); 

Then you can use this service in your controllers and exchange data with each controller using the setData() and getData() functions of the service.

+5
source share

You cannot demand from the controller. You can require a directive that is one of the parents of the current directive.

  <foo> <bar /> </foo> // in foo controller: 'fooController' // in bar require: '^foo' // ^ means to search it up in the tree 

Here, the bar may require foo, and it will have a foo controller: http://jsfiddle.net/Zmetser/kHdVX/ In this example, fooController will be initialized once.

  <foo /> <bar /> // in foo controller: 'fooController' // in bar controller: 'fooController' 

Here bar and foo has its own instance of fooController: http://jsfiddle.net/Zmetser/QypXn/

+4
source share

All Articles