2015-11-03 68 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

相关问题