reptilicus
reptilicus

Reputation: 10397

Angular using another directive's controller?

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);
    }
  };
});

Upvotes: 0

Views: 517

Answers (1)

Karen Zilles
Karen Zilles

Reputation: 7661

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);
}

Upvotes: 2

Related Questions