0

I am learning Angular and need to create some custom filters.

Do I create one filters.js file and put all my filters in there similar to all my reusable factory.js?

Eg: I have a utilsFactory.js and I put reusable functions in here.

Does this then get injected into the controllers? Or is this loaded in the $rootscope somewhere?

I have seen many examples on how to create them but not how to store and manage them and how to access them properly

filter.js

angular.module('achApp', [])
.filter('myUpperCase', function(){
    return function(value){
        return String(value).toUpperCase();
    }
});

Controller

(function(){

    var DevbController = function($scope, utilsFactory, $filter){
         $scope.greeting = 'hello';
    };

     DevbController.$inject = ['$scope', 'utilsFactory', '$filter'];

    angular.module('achApp')
       .controller('DevbController', DevbController)

}());
ottz0
  • 2,595
  • 7
  • 25
  • 45

1 Answers1

0

Filters are generally created for use in your templates (HTML). For example:

<p>{{somethingOnScope | myFilter}}</p>

You can use them in your JS files by injecting $filter, and then getting a reference to your filter like: $filter('myFilter');

You can see usage examples in the filter documentation:

https://docs.angularjs.org/api/ng/filter/filter

Where and how exactly you register your filters is a matter of style. I personally try to follow john papa's advice and create only one injectable item per file.

On another subjective note, I prefer to minimize the use of filters, especially custom ones. If you want to use them primarily in your JS, a service/factory feels cleaner to me, and if you're tempted to create one for use in your templates, often you can instead just change the thing before putting it on the scope.

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149
  • I have made one per file in a folder called filters and have this referenced in my index.html file. Where do you gain reference to it $filter('myFilter')? – ottz0 Jan 05 '16 at 04:32
  • Instructions for using `$filter` are in that documentation page. If its too confusing, than maybe it would be good to go back and run through an AngularJS tutorial or two? Here is another SO post talking about using `$filter` in a controller if that helps: http://stackoverflow.com/questions/14302267/how-to-use-a-filter-in-a-controller – Zach Lysobey Jan 05 '16 at 15:39