Metaprogramming AngularJS Filters

353 views Asked by At

Is there a way to dynamically create filters in Angular? Below I have simple filters that returns only certain properties of an array of objects.

module.filter("firstAndLastName", function() {
    return function(input) {
        return input.map(function(obj) {
            return obj.first_name + " " + obj.last_name
        });
    }
})

module.filter("gradYear", function() {
    return function(input) {
        return input.map(function(obj) {
            return obj.grad_year
        });
    }
})

If I wanted to grab the "email_address" of an array of objects, and injected. Is there a way to dynamically create it at runtime?

module.controller("someController", ["emailAddressFilter",
    function(emailAddressFilter) {
        // use emailAddressFilter
    }
])

A more general question

How can we dynamically create Angular components?

1

There are 1 answers

1
Deblaton Jean-Philippe On

Do not forget that in Javascript, everything is created at runtime.

Instead of this :

module.filter("whatEverFilter", function() {
  return function(input) {
    return input.map(function(obj) {
      return obj.first_name + " " + obj.last_name
    });
  }
});

You can simply do the following :

module.filter("whatEverFilter", function() { 
  //stringArray can be eg : ["first_name","last_name"]
  return function(input, stringArray) {
    return input.map(function(obj) {  
      var strReturn = obj[stringArray[0]]
      for(var i=1; i<stringArray.length ;i++){
          strReturn += " ";
          strReturn += obj[stringArray[i]];
      }
      return strReturn;
    });
  }
})