2015-11-03 70 views
4

我需要角度指令的鏈接函數中的$ filter,但是沒有辦法將$ filter作爲參數傳遞給鏈接函數。

app.directive('myDirective', function($compile) { 
    return { 
    restrict: 'A', 
    scope: { 
     ngModel: '=', 
    }, 
    require: 'ngModel', 
    link: function($scope, elem, attr, ctrl) { 

    } 
    }; 
}); 

http://plnkr.co/edit/XpnY5dq7rnl2sWXlsN4t?p=preview

如何訪問鏈接函數內部的$過濾器?

回答

9

只需將其注入到您的實際指令函數中,然後就可以在整個指令中使用它(包括鏈接函數)。

app.directive('myDirective', function($compile, $filter){ 
    return { 
     restrict: 'A', 
     scope: { 
      ngModel: '=', 
     }, 
     require: 'ngModel', 
     link: function($scope, elem, attr, ctrl) { 
      // call $filter here as you wish 

     } 
    }; 
}); 

只要將鏈接函數看作不直接處理角度注入系統的私有指令函數即可。通過注入主指令功能,您基本上可以說所有內部函數都可以使用它。

+0

u能交一個plnkr請。 – Vivek

+0

不太確定答案的複雜程度,但下面是一個更新程序:http://plnkr.co/edit/3RhXJN0sIDp4Ps6c5kDS?p=preview –

4

你需要注入的$filter依賴性,所有的自定義服務/工廠和在建的角度提供商($超時,$過濾器),應注入如下

app.directive('myDirective', ['$compile','$filter',function($compile,$filter) { 
    return { 
    restrict: 'A', 
    scope: { 
     ngModel: '=', 
    }, 
    require: 'ngModel', 
    link: function($scope, elem, attr, ctrl) { 
     console.log($filter); 
    } 
    }; 
}]); 

http://plnkr.co/edit/JUE1F83l1BC0LTlO7cxJ?p=preview

相關問題