我正在开发一个Angular库,并寻找一种使用decorator模式扩展指令的方法:
angular.module('myApp', []).decorator('originaldirectiveDirective', [
'$delegate', function($delegate) {
var originalLinkFn;
originalLinkFn = $delegate[0].link;
return $delegate;
}
]);
使用这种模式扩充原始指令的最佳方式是什么?(示例用法:在不直接修改指令代码的情况下,对指令进行额外的监视或额外的事件侦听器(。
您可以很容易地修改或扩展指令的controller
。如果您要查找的是link
(如您的示例中所示(,则不会太难。只需在config
阶段修改指令的compile
函数即可。
例如:
HTML模板
<body>
<my-directive></my-directive>
</body>
JavaScript
angular.module('app', [])
.config(function($provide) {
$provide.decorator('myDirectiveDirective', function($delegate) {
var directive = $delegate[0];
directive.compile = function() {
return function(scope) {
directive.link.apply(this, arguments);
scope.$watch('value', function() {
console.log('value', scope.value);
});
};
};
return $delegate;
});
})
.directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope) {
scope.value = 0;
},
template: '<input type="number" ng-model="value">'
};
});
现在,您已经将myDirective
修饰为在value
发生更改时记录它。
此处为相关的plunkerhttps://plnkr.co/edit/mDYxKj