Angularjs: directive defined controllers communicating with child directives
I think I'm missing something when it comes to directives interacting with
internal controllers. The API documentation is pretty poor on the Angular
site. As far as I can tell, in order to access a controller located within
a parent directive you simply need to set require: '^parentDirective' and
add a fourth argument to the link: attribute on the child directive.
I am unable to access the controller with either $scope or the fourth
argument (I'm using $ctrls).
I wish to be able to push data to an injected service on the parent
directive.
Service:
app.service( 'injectedService', function() {
var service = {
spies: [],
addSpy: function( spy ) {
service.spies.push( spy );
}
};
return service;
});
Parent directive:
app.directive ( 'parentDirective', [ '$window', 'injectedService',
function( $window, injectedService ) {
return {
restrict: 'A',
controller: function( $scope ) {
$scope.test = 'hello';
$scope.addSpy = injectedService.addSpy;
},
link: function( $scope, $element, $attrs ) {
console.log( $scope.test ); //hello
}
};
}]);
Child directive:
app.directive( 'childDirective', [ function() {
return {
restrict: 'A',
require: '^parentDirective',
link: function( $scope, $element, $attrs, $ctrls ){
console.log( $scope.test ); //undefined
console.log( $ctrls.test ); //undefined
console.log( $ctrls.$scope.test ); //undefined
$scope.addSpy({
id: 'test'
}); //error: $ctrls/$scope.addSpy not a function
}
};
}]);
No comments:
Post a Comment