2

I have a small question.

I have this json object that

var map = {
    key1 : {filter:'bytes',value: 100000000},
    key2 : {filter:'ratio',value: 1.25}
};

I would like to use it with ng-repeat

<div ng-repeat="key in map"> {{key.value | key.filter}}</div>

How can I accomplish this behaviour to get predefined filters implemented while in ng-repeat?

2
  • basicly your syntax shows key.value, or if that is null/undefined key.filter. You will want to tell angular to use a filter. I believe the proper way to do so is {{key.value | filter:key.filter}} Commented Jul 30, 2015 at 14:01
  • do you want do {{val.value | ratio }} and {{val.value | bytes}} but select filter dynamically? Commented Jul 30, 2015 at 14:28

2 Answers 2

1

If i understand right, you want get something like

<div ng-repeat="key in map"> {{100000000 | bytes }}</div>
<div ng-repeat="key in map"> {{1.25 | ratio }}</div>

But angular raise error when try parse expression, instead get filter name from variable. So you can add a filter, that would be apply to source filter by name, something like

.filter('applyFilter',function($filter){
    return function(source, filterName){
        return $filter(filterName)(source);
    }
})

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.map = {
      key1: {
        filter: 'bytes',
        value: 100000000
      },
      key2: {
        filter: 'ratio',
        value: 1.25
      }
    };
  }).filter('bytes',function(){
    return function(a){
      return a + ' bytes';
    }
  }).filter('ratio',function(){
    return function(a){
      return 'ratio: ' + a;
    }
  }).filter('applyFilter',function($filter){
    return function(source, filterName){
      return $filter(filterName)(source);
      }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
      <div ng-repeat="key in map"> {{key.value | applyFilter: key.filter }}</div>
      
    </div>

Sign up to request clarification or add additional context in comments.

Comments

1

You can build a filter that invokes your customer filter like this:

filter('invokerFilter', function($filter) {
    return function(value ,filterName) {
        return $filter(filterName)(value) ;
};

I created an example for you here

3 Comments

I did not. But I did something similar with the approach above several times.
it doesnt have to be an array, it will display the key.value, filtered by key.filter. This should work. Did you try it yourself?
yep, and get error Error: [filter:notarray] Expected array but received: 1.25, from doc: This error occurs when filter is not used with an array, some plunkr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.