Directives can be decorated just like services and we can modify or replace any of it's functionality. Note that directive itself is accessed at position 0 in $delegate array and name parameter in decorator must include Directive
suffix (case sensitive).
So, if directive is called myDate
, it can be accessed using myDateDirective
using $delegate[0]
.
Below is simple example where directive shows current time. We'll decorate it to update current time in one second intervals. Without decoration it will always show same time.
<body>
<my-date></my-date>
</body>
angular.module('app', [])
.config(function($provide) {
$provide.decorator('myDateDirective', function($delegate, $interval) {
var directive = $delegate[0]; // access directive
directive.compile = function() { // modify compile fn
return function(scope) {
directive.link.apply(this, arguments);
$interval(function() {
scope.date = new Date(); // update date every second
}, 1000);
};
};
return $delegate;
});
})
.directive('myDate', function() {
return {
restrict: 'E',
template: '<span>Current time is {{ date | date:\'MM:ss\' }}</span>',
link: function(scope) {
scope.date = new Date(); // get current date
}
};
});