0
votes

If I have two directives, and need to have one of them use the controller of the other one, what is the best way to accomplish something like that in angular? I'm trying to use the require: otherDirective stuff I see in the docs, but I'm getting an

Error: No controller: dirOne

from the following example. I was under the impression that by specifying dirOne in the require statement, dirTwo would have access to the controller of dirOne. What am I doing wrong here?

Here's a plunkr as well

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

app.directive('dirOne', function() {
  return {
    controller: function($scope) {

      $scope.options = {
        "opt1" : true, 
        "opt2" : false, 
        "opt3" : false, 
      }

      this.getOptions = function() {
        return $scope.options;
      };

    }
  };
});

app.directive('dirTwo',function() {
  return {
    require: 'dirOne',
    link: function(scope, element, attrs, dirOneCtrl) {
      $scope.options = dirOneCtrl.getOptions();
      alert($scope.options);
    }
  };
});
1
Based on what's in the docs what you specify in require must be a controller it will attempt to find (my guess is it then creates a new instance, so this is probably not what you want). If you want to "share" information between two elements there's two ways I'm aware of in Angular, 1 create a service, the service is a singleton so updates made to properties of the service can be seen throughout. 2 use $on $emit $broadcast to setup an event structure for passing information. (3 maybe use a parent scope, but seems fragile)shaunhusain

1 Answers

2
votes

http://plnkr.co/edit/vq7vvz

There were two problems with your plunkr:

In order for a directive to require the controller of another directive, the two directives have to be on the same element, or if you use the ^ notation, the required directive can be on a parent element.

  <div dir-one dir-two></div>

Also, in the second directive you called your parameter "scope" but then tried to use it as "$scope".

link: function(scope, element, attrs, dirOneCtrl) {
  scope.options = dirOneCtrl.getOptions();
  alert(scope.options);
}