Here is a basic directive called "base":
angular.module("base", [])
.directive("base", function() {
return {
restrict: "A",
scope: true,
controller: function($scope) {
this.setHeader = function(header) {
$scope.header = header;
}
this.setBody = function(body) {
$scope.body = body;
}
this.setFooter = function(footer) {
$scope.footer = footer;
}
},
templateUrl: "base.html"
}
});
I am passing data to this directive like this:
.directive("custom", function() {
return {
restrict: "E",
require: "^base",
scope: {
ngModel: "="
},
link: function($scope, $element, $attrs, baseCtrl) {
//Do something with the data or not...
baseCtrl.setHeader($scope.ngModel.header);
baseCtrl.setBody($scope.ngModel.body);
baseCtrl.setFooter($scope.ngModel.footer);
}
}
});
However, when I create a list of my custom
directives, there is a slight delay before they render. You can see this behavior in the Plunker example. (The list cells initially appear empty before displaying the directives)
The idea behind this approach is to reuse the template of the base
directive and only pass in the necessary display data. While $scope.data
suffices in this case, there may be instances where some preprocessing is required. Instead of burdening the data-querying controller with this task, I prefer to delegate it to the directive, for cleaner separation of concerns.
This raises two questions:
- Is there a way to speed up directive rendering and eliminate the flickering as seen in the example?
- Is this methodology considered a best practice for reusing directives in Angular?