Reputation: 6422
I have two directives, and I'd like to expose an API in one of them for others to use. Following the guidance from this example I'm getting this error when I require the other directive's controller:
Error: No controller: foo
at Error (<anonymous>)
at getControllers (http://localhost:3000/vendor/angular/angular.js:4216:19)
at nodeLinkFn (http://localhost:3000/vendor/angular/angular.js:4345:35)
at compositeLinkFn (http://localhost:3000/vendor/angular/angular.js:3953:15)
at publicLinkFn (http://localhost:3000/vendor/angular/angular.js:3858:30)
at <error: illegal access>
at Object.Scope.$broadcast (http://localhost:3000/vendor/angular/angular.js:8243:28)
at http://localhost:3000/vendor/angular/angular.js:7399:26
at wrappedCallback (http://localhost:3000/vendor/angular/angular.js:6780:59)
at wrappedCallback (http://localhost:3000/vendor/angular/angular.js:6780:59) <bar class="ng-scope">
My directives are defined as follows:
})
.directive('foo', function() {
return {
restrict: 'E',
template: '<h1>Foo</h1>',
controller: function($scope) {
$scope.someArray = [];
this.doStuff = function() {
$scope.someArray.push('abc');
}
},
link: function(scope, element, attrs) {
}
}
})
.directive('bar', function() {
return {
require: 'foo',
restrict:'E',
template: '<h1>Bar</h1>',
link: function(scope, element, attrs, fooCtrl) {
element.bind('mouseent', function() {
fooCtrl.doStuff();
})
}
}
})
Does anyone know why the second directie can't see the first directive's controller?
Thanks,
Upvotes: 3
Views: 2492
Reputation: 35478
require
property in directive definition object injects the controller(s) to the linking function.
But: The directive does not initiate on its own, you need also declare the foo
directive in the element. Like: <div foo="hello" bar="world"></div>
.
Also, it has 2 prefixes which can be combined.
?
: "Make requirement optional", no errors are raised.^
: "Look for it in the parent elements", normally the required directive iw expected to be at the same element. This makes it search in the parent elements.Upvotes: 4