如何使用angular的装饰器模式扩充指令的链接功能? [英] How can I augment a directive's link function with angular's decorator pattern?
问题描述
我正在研究Angular库,正在寻找一种使用装饰器模式扩展指令的方法:
I'm working on an Angular library and looking for a way to extend a directive using the decorator pattern:
angular.module('myApp', []).decorator('originaldirectiveDirective', [
'$delegate', function($delegate) {
var originalLinkFn;
originalLinkFn = $delegate[0].link;
return $delegate;
}
]);
使用此模式来扩展原始指令的最佳方法是什么? (示例用法:在指令上具有其他监视程序或事件监听器,而无需直接修改其代码).
What would be the best way to augment the original directive using this pattern? (Example usage: to have additional watches or extra event listeners on the directive without modifying it's code directly).
推荐答案
您可以很容易地修改或扩展指令的controller
.如果您要查找的是link
(如您的示例中所示),那么难度就没有那么大了.只需在config
阶段修改指令的compile
函数.
You can modify or extend directive's controller
quite easily. If it's link
you are looking for (as in your example), it's not that much harder. Just modify directive's compile
function in config
phase.
例如:
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
更改时登录.
Now you have decorated myDirective
to log value
when ever it has changed.
此处的相关监听器 https://plnkr.co/edit/mDYxKj
这篇关于如何使用angular的装饰器模式扩充指令的链接功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!