I created a custom filter for my angularjs project similar to the following fiddle http://jsfiddle.net/tUyyx/.
myapp.filter('truncate',function(text,length){
var end = "..."
text = text.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
if (isNaN(length))
length = 23;
if (text.length <= length || text.length - end.length <= length) {
return text;
}
else {
return String(text).substring(0, length-end.length) + end;
}
});
but when I use the filter i get the following error
Error: Unknown provider: textProvider <- text <- truncateFilter
at Error (<anonymous>)
at http://localhost/javascripts/lib/angular.min.js:28:236
at Object.c [as get] (http://localhost/javascripts/lib/angular.min.js:26:13)
at http://localhost/javascripts/lib/angular.min.js:28:317
at c (http://localhost/javascripts/lib/angular.min.js:26:13)
at Object.d [as invoke] (http://localhost/javascripts/lib/angular.min.js:26:147)
at http://localhost/javascripts/lib/angular.min.js:28:335
at Object.c [as get] (http://localhost/javascripts/lib/angular.min.js:26:13)
at http://localhost/javascripts/lib/angular.min.js:99:481
at o (http://localhost/javascripts/lib/angular.min.js:66:471)
I have created my module like this.
var myapp = angular.module('myapp', ['ngResource']);
What am i doing wrong?
If you look at the code in that jsFiddle, that filter function returns a function that takes text
etc as an argument. It should be something like this:
myapp.filter('truncate',function(){
return function(text, length) {
var end = "..."
text = text.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
if (isNaN(length))
length = 23;
if (text.length <= length || text.length - end.length <= length) {
return text;
}
else {
return String(text).substring(0, length-end.length) + end;
}
}
});
The reason you got "Unknown provider: textProvider" is because you have text
as an argument to your filter. That makes Angular look for a service called text
which doesn't exist. It's the function that you return that takes text
as an argument.
Think of it this way, the first function (the one you pass into angular.filter) is the function that first creates the filter. That function is only executed once in your application. The responsibility of that function is to create another function and return it, and the function it returns is your filter. The reason you have a function that returns a function is to let you return different implementations depending on your system. Perhaps something like this:
myapp.filter('truncate', function(myService) {
if (myService.someCondition()) {
return function(text, length) {
// return the text as usual
}
} else {
return function(text, length) {
// return the text and do some other things as well
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With