2017-03-07 46 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; 
}) 
相關問題