Angular Custom filters: match value with value in array and get corresponding name

Issue

Blockquote

I want to convert a number to a animal with a Angular filter.

I have the following ng-repeat:

<div ng-repeat="speed in speeds track by $index">
   You're faster than a <span ng-bind="speed.value | speedToAnimal"></span>
</div>

speed.value wil give you a value like 42.9

Ik want to match this speed value with a speed value in a array where speeds are linked to animals.

For example this is the array I have:

var animals = [
    {
      "speed": 33.7,
      "animal": 'pig',
    },
    {
      "speed": 40.2,
      "animal": 'Dog',
    },
    {
      "speed": 45.4,
      "animal": 'Horse',
    }
    ...
];

The speed value 42.9 is higher than the speed value of the dog in the array but lower than the speed value of the horse so I want the filter to turn the value 42.9 in to “Dog” so the end result wil be: You’re faster than a Dog, instead of You’re faster than a 42.9

I know how to call a filter but I don’t know how build one.
Call filter: ng-bind="speed.value | speedToAnimal
filter:

app.filter('speedToAnimal', function() {
  return function(input, optional1, optional2) {
    // Do filter work here
    return output;
  }
});

jsfiddle

Solution

With some help from the answer of Amulya Kashyap this is my working solution:

<div ng-repeat="speed in speeds track by $index">
   You're faster than a <span ng-bind="speed.value | speedToAnimal"></span>
</div>

The Filter a came up with:

app.filter('speedToAnimal', function () {
    return function (value) {

        var animals = [
            {"speed":12,"animal":"Field Mouse"},
            {"speed":13,"animal":"House Mouse"},
            {"speed":16,"animal":"Camel"},
            {"speed":18,"animal":"Pig"},
            {"speed":20,"animal":"Gray Squirrel"},
            {"speed":22,"animal":"Sea Lion"},
            {"speed":24,"animal":"Sheep"},
        ];

        if(!animals) return;

        var curSpeed = value;
        var len = animals.length - 1;
        while(len >= 0){
            if(curSpeed >= animals[len].speed){
                return animals[len].animal;
            }
            len--;
        }
    };
});

Answered By – user1242574

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published