Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple custom filters within a single module in Angularjs

Tags:

angularjs

I'm following this tutorial and created the underneath custom filters accordingly. The last one however causes the first one to disappear; when you use the truncate filter it an exception. How do you create multiple filters within a module?

angular.module('filters', []).filter('truncate', function () {
    return function (text, length, end) {
        if (isNaN(length))
            length = 10;

        if (end === undefined)
            end = "...";

        if (text.length <= length || text.length - end.length <= length) {
            return text;
        }
        else {
            return String(text).substring(0, length-end.length) + end;
        }

    };
});


angular.module('filters', []).filter('escape', function () {
    return function(text) {
      encodeURIComponent(text);  
    };
});
like image 272
bicycle Avatar asked Oct 01 '13 04:10

bicycle


3 Answers

angular.module('filters', []).filter("truncate", function() {})
                             .filter("escape", function() {});
like image 82
geniuscarrier Avatar answered Oct 18 '22 21:10

geniuscarrier


The second one should be declared using

angular.module('filters').filter(....)

syntax.

The syntax you are using creates a new module everytime.

like image 39
Chandermani Avatar answered Oct 18 '22 19:10

Chandermani


One way to separate the filters out into individual files would be to create a filter module that requires the filters individually:

// init.js
angular.module('application', ['application.filters'])  

// filters.js    
angular.module('application.filters', [
               'filters.currencyCents',
               'filters.percentage',
               ]);  


// percentage.js        
angular.module('filters.percentage', []).filter('percentage', function() {
  return function(decimal, sigFigs) {
    ...
  };
});  
like image 27
jz999 Avatar answered Oct 18 '22 19:10

jz999