user3174311
user3174311

Reputation: 1983

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. Am I missing something?

Upvotes: 0

Views: 124

Answers (1)

aUXcoder
aUXcoder

Reputation: 1052

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.

// 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;
}});

Upvotes: 1

Related Questions