角度自定义过滤器:将值与数组中的值匹配并获取相应的名称

时间:2016-03-12 18:41:07

标签: arrays angularjs ionic-framework angular-filters

  

块引用

我想用角度滤镜将数字转换为动物。

我有以下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会给你一个类似42.9的值

我希望将此速度值与速度与动物相关联的数组中的速度值进行匹配。

例如,这是我拥有的数组:

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

速度值42.9高于阵列中狗的速度值但低于马的速度值所以我希望过滤器将值42.9变为“狗”,因此最终结果将是:你比狗快,而不是你快42.9

我知道如何调用过滤器,但我不知道如何构建过滤器 呼叫过滤器:ng-bind="speed.value | speedToAnimal
过滤器:

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

jsfiddle

2 个答案:

答案 0 :(得分:0)

亲爱的

以下是您的代码的工作小提琴:Fiddle of Your Code

  1. 现在,这也是你的代码:
  2. HTML PART:

    <div ng-controller="MyCtrl">
     <legend> Enter Speed</legend> 
    <input type="text" ng-model="speed.value" required />
    <button type="button" ng-click="calc()">Get Animal</button>
    
    <span>{{filteredAnimals}}</span>
    </div>
    

    控制器代码

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function($scope) {
        $scope.animals = [
        {
          "speed": 33.7,
          "animal": 'pig',
        },
        {
          "speed": 40.2,
          "animal": 'Dog',
        },
        {
          "speed": 45.4,
          "animal": 'Horse',
        }];
    
        $scope.calc = function(){
            $scope.curSpeed = $scope.speed.value;
            var len = $scope.animals.length - 1;
            var filteredAnimals;
            while(len >= 0){
                if($scope.curSpeed >= $scope.animals[len].speed){
                    filteredAnimals = $scope.filteredAnimals = $scope.animals[len].animal;
                    break;
                }
                len--;
            }
        }
    });
    

    谢谢&amp;干杯

答案 1 :(得分:0)

在Amulya Kashyap回答的帮助下,这是我的工作解决方案:

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


Filter a想出了:

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--;
        }
    };
});