我正在开发一个 Angular 库,并寻找一种使用装饰器模式扩展指令的方法:
angular.module('myApp', []).decorator('originaldirectiveDirective', [
'$delegate', function($delegate) {
var originalLinkFn;
originalLinkFn = $delegate[0].link;
return $delegate;
}
]);
使用此模式增强原始指令的最佳方法是什么?
(示例用法:在指令上有额外的监视或额外的事件侦听器,而无需直接修改其代码)。
您可以修改或扩展指令controller
很容易。如果它是link
你正在寻找(如你的例子),这并没有那么难。只需修改指令的compile
函数于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
to log value
它什么时候改变过。
相关的笨蛋在这里https://plnkr.co/edit/mDYxKj https://plnkr.co/edit/mDYxKj
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)