简体   繁体   English

AngularJS 中的自定义过滤器

[英]Custom filter in AngularJS

I just made a simple custom filter to strip some chars from a string我刚刚制作了一个简单的自定义过滤器来从字符串中删除一些字符

angular.module('myApp.filters').filter('myFilter', function() {
return function(string) {
    string = string.replace('[', '');
    string = string.replace(']', '');
    string = string.replace('","', ', ');
    string = string.replace('"', '');

    return string;
}
});

then in the template然后在模板中

<td>[[res[0].names | myFilter]]</td>

but I keep getting this error:但我不断收到此错误:

Unknown provider: myFilterFilterProvider <- myFilterFilter

I also tried to inject this filter in the controller responsible for that template but no luck.我还尝试将此过滤器注入负责该模板的 controller 中,但没有运气。 Am I missing something?我错过了什么吗?

You can build your filter as an angular module and then add that module as a application dependency or just add the filter in the application declaration.您可以将过滤器构建为 angular 模块,然后将该模块添加为应用程序依赖项,或者仅在应用程序声明中添加过滤器。

// create a module
angular.module('myApp.filters', []).filter('myFilter', function() {
  return function(string) {
    string = string.replace('[', '');
    string = string.replace(']', '');
    string = string.replace('","', ', ');
    string = string.replace('"', '');
    return string;
  }
});
// add the module as a dependency
angular.module('myApp', ['myApp.filters']);

or或者

// in the application declaration
angular.module('myApp', []).filter('myFilter', function() {
  return function(string) {
    string = string.replace('[', '');
    string = string.replace(']', '');
    string = string.replace('","', ', ');
    string = string.replace('"', '');
    return string;
}});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM