You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
app.config(function($provide){$provide.decorator('fooDirective',function($delegate){vardirective=$delegate[0];directive.scope.fn="&";//backup old link method 备份旧的linkvarlink=directive.link;//extend compile 扩展compiledirective.compile=function(){returnfunction(scope,element,attrs){link.apply(this,arguments);element.bind('click',function(){scope.$apply(function(){scope.fn();});});};};return$delegate;});});
备份旧的compile方法,执行,对返回的link方法进行扩展
app.config(function($provide){$provide.decorator('fooDirective',function($delegate){vardirective=$delegate[0];varcompile=directive.compile;directive.compile=function(tElement,tAttrs){varlink=compile.apply(this,arguments);tElement.append('<div>Added in the decorator</div>');returnfunction(scope,elem,attrs){link.apply(this,arguments);// We can extend the link function here};};return$delegate;});});
使用$provide.decorator方法去扩展angular现有指令
几个切入点
扩展scope参数
使用angular.extend方法合并scope对象,该方式在1.2.x下是好的,到了1.3就不work了,不过有workaround方法,就是直接向directive.$$isolateBindings对象里面push你的参数,可以参看下面的例子
替换模板
直接对directive对象的templateUrl或tenmplate属性直接赋上你的模板:
扩展或替换controller
扩展或替换 controller 或者 link 方法:
替换是直接附上新的函数即可
扩展是使用JavaScript函数进行继承,将要扩展函数的this上的属性和方法,全部继承过来。具体可以参看gist, 具体还没实践,但是理论上肯定是可以的.
另一种扩展controller的方法,使用$controller,测试后有些问题(会丢失一些方法),大家可以研究一下(来自参考资料的方法)
扩展link或compile (来自参考资料的方法)
备份link函数对其进行扩展
备份旧的compile方法,执行,对返回的link方法进行扩展
Example
扩展Bootstrap-UI Alert Directive
扩展Bootstrap-UI Dropdown Directive
参考资料:
Experiment: Decorating Directives
AngularJS in Patterns (Part 2). Services.
The text was updated successfully, but these errors were encountered: