I've found a few similar questions on stackoverflow but no satisfying answer.
I prefer to hold most of directives logic in their controllers with bindToController
and controllerAs
.
So the standard communication beetwen 2 directives looks like:
<parent-directive>
<child-directive></child-directive>
</parent-directive>
angular.module('app').
directive('parent', function() {
return {
scope: {},
restrict: 'E',
controller: function() {
this.doSomething = function() {
console.log('Consider it done!');
};
},
controllerAs: 'vm'
}
}).
directive('child', function() {
return {
restrict: 'E',
require: '^parent',
link: function($scope, $element, $attrs, parentController) {
parentController.doSomething();
}
}
});
This pattern of course works as expected. But when I want the children directive also use controller instead of linking function, I've to do something like this:
.directive('child', function() {
return {
restrict: 'E',
require: ['child', '^parent'],
controllerAs: 'vm',
controller: function() {
this._parentController = null;
var vm = this;
this.doSomethingInChild = function() {
var iDepnedOnThis = this._parentController.doSomething();
//do something more with above call result...
}.bind(this);
}
link: function($scope, $element, $attrs, controllers) {
var vm = controllers[0];
vm._parentController = controllers[1];
}
}
});
It also works, but I'm not sure if this is clean and the best solution. Is there any way to get rid of the parentController to childController assignment to in linking function?