Designing deep directives in Angular
I know the isolated area and read some resources about Angular. Now I am facing a problem: suppose I have very deep directives:
A wraps B wraps C wraps D wraps E
X wraps Y wraps D wraps E
A, B, C, D, E, X, Y are directives. D and E need some information about what is being transmitted to their highlighted areas, I call this information info: '='
. It info
belongs to A or X. So if I need to use info
in D and E, I have to pass it along the paths: A -> B -> C -> D -> E
or X -> Y -> D -> E
. This means that B, C, or Y must create their own isolated areas to store the value info
. Too deep! If in the future I add some directives in the middle of the paths, I have to do the same as above. I don't think this is a good design.
Any body can give me some suggestions on how to solve this design problem in Angular?
OK. You could:
1 - Store information inside the service and just enter it where you need it.
2 - Allow directives to communicate with each other through the controller. So, for example, if you want the E directive to receive the A information form directive, A must have a controller and some sort of getter method, the E directive will require that controller and use the get method inside the link function. Easier to visualize with code.
.directive('aDir', function () {
return {
restrict: 'E',
transclude: true,
template: '<p>aDir: {{info}}<span ng-transclude></span></p>',
scope: {
info: '='
},
controller: function ($scope) {
this.getInfo = function () {
return $scope.info;
};
},
link: function (scope, elm, attrs) {
}
};
})
.directive('eDir', function () {
return {
restrict: 'E',
template: '<p>eDir: {{info}}</p>',
require: '^aDir',
scope: { },
link: function (scope, elm, attrs, aDirController) {
scope.$watch(function () {
return aDirController.getInfo();
}, function (newVal, oldVal) {
scope.info = newVal;
});
}
};
});
Here is JSBin .
You have more information about the require attribute here.
How to use the service to store data. Services are singleton objects in Angular. Therefore, if you set a value in one place, it will be visible in another.
So put the service in A, set the value there. Inject the service in D as well (or where needed) and read the value there.
You will probably have to set the clock to react to the change in the place (s) you read it.