2017-03-07 62 views
2

试图遵循Angular Decorator指南(https://docs.angularjs.org/guide/decorators)中的模板,我尝试创建一个指令并对其进行装饰。为什么我装饰的指令不会覆盖AngularJS中的原始方法?

该指令应显示当前日期/时间。我添加了一个(无用的)装饰器来修改link函数,以便指令显示字符串“today”而不是日期/时间。

出于某种原因,似乎我被覆盖的link函数没有被调用。原来被调用。为什么是这样?

代码为http://plnkr.co/edit/uvtBiN5vNSjk5I89t99C?p=preview(及以下):

angular.module('app', []); 

angular.module('app').directive('myElement', function(){ 
    return { 
    template: 'Today is {{ date }}', 
    link: function(scope, element, attrs){ 
     console.log('original link called') 
     scope.date = new Date(); 
    } 
    } 
}) 

angular.module('app').decorator('myElementDirective', function($delegate){ 

    $delegate[0].link = function(scope){ 
    console.log('calling delegate link') 
    scope.date = "today" 
    } 
    return $delegate; 
}) 

回答

3

当更换链接功能,编译功能,需要更换为好。

angular.module('app').decorator('myElementDirective', function($delegate){ 

    $delegate[0].link = function(scope){ 
    console.log('calling delegate link') 
    scope.date = "today" 
    } 
    //------------------------------------ 
    //REPLACE compile function 
    $delegate[0].compile = function() { 
    return $delegate[0].link; 
    }; 
    //------------------------------------ 
    return $delegate; 
}) 

当指令定义对象(DDO)省略编译函数,该$compileProvider.directive()登记方法添加一个返回到所述连接功能的引用。编译函数需要更新以返回对新链接函数的引用。

$compile service忽略了DDO的link属性。它只使用compile属性。

2

链接函数是在AngularJS只是语法糖。如果你使用它,AngularJS将使用该链接函数生成一个编译函数。但一旦完成,替换链接功能将不起作用。

相反,你应该替换为自己编译的函数,返回新的链接功能:

angular.module('app').decorator('myElementDirective', function($delegate){ 
    var originalLink = $delegate[0].link; 

    $delegate[0].compile = function() { 
     return function(scope, element, attrs) { 
     originalLink.apply($delegate[0], arguments); 
     scope.date = "today"; 
     }; 
    }; 

    return $delegate; 
}) 
相关问题