Angular js directives can be nested or be made interoperable.
In this example, directive Adir exposes to directive Bdir it's controller $scope, since Bdir requires Adir.
angular.module('myApp',[]).directive('Adir', function () {
return {
restrict: 'AE',
controller: ['$scope', function ($scope) {
$scope.logFn = function (val) {
console.log(val);
}
}]
}
})
Make sure to set require: '^Adir' (look at the angular documentation, some versions doesn't require ^ character).
.directive('Bdir', function () {
return {
restrict: 'AE',
require: '^Adir', // Bdir require Adir
link: function (scope, elem, attr, Parent) {
// Parent is Adir but can be an array of required directives.
elem.on('click', function ($event) {
Parent.logFn("Hello!"); // will log "Hello! at parent dir scope
scope.$apply(); // apply to parent scope.
});
}
}
}]);
You can nest your directive in this way:
<div a-dir><span b-dir></span></div>
<a-dir><b-dir></b-dir> </a-dir>
Is not required that directives are nested in your HTML.