javascript - 在for循环中过滤掉

标签 javascript angularjs arrays angularjs-filter

我正在尝试创建一个下拉列表,当我创建它时,我想按字段进行过滤。例如:

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>

    <div ng-app="myApp" ng-controller="myCtrl">

    <select ng-model="cost" ng-options="x.cost for x in costs">
    </select>

    </div>

    <script>
    var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
        $scope.costs = [{'cost': 1, 'difficulty' : 3}, {'cost': 2, 'difficulty' : 2}, {'cost': 3, 'difficulty' : 3}];
    });
    </script>

    <p>This example shows how to fill a dropdown list using the ng-options directive.</p>

    </body>
    </html>

在此示例中,我将如何按难度进行过滤?是否可以做类似的事情

ng-options="x.cost for x in costs where x.difficulty >= 3"

最佳答案

使用自定义过滤器,如下所示:

  $scope.myFilter = function(x) {
    return x.difficulty >= 3;
  }

并将其应用到 ng-options 中,如下所示:

 <select ng-model="cost" ng-options="x.cost for x in costs | filter : myFilter">
 </select>

下面的演示:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.costs = [{
    'cost': 1,
    'difficulty': 3
  }, {
    'cost': 2,
    'difficulty': 2
  }, {
    'cost': 3,
    'difficulty': 3
  }];

  $scope.myFilter = function(x) {
    return x.difficulty >= 3;
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <select ng-model="cost" ng-options="x.cost for x in costs | filter : myFilter">
    </select>

  </div>

  <p>This example shows how to fill a dropdown list using the ng-options directive.</p>

</body>

</html>

关于javascript - 在for循环中过滤掉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309645/

相关文章:

javascript - 如何防范Javascript中的客户端DOM代码注入(inject)漏洞?

javascript - 使用 Gmaps4rails gem 调用 ReplaceMarkers 后 Gmaps.map.callback 不起作用?

javascript - 如何使Angular的服务可供独立对象使用; Angular JS

javascript - Web Workers 会对 ionic 应用程序有益吗?

java - 找出数组是否包含唯一元素

php - 如何将多维数组放入双引号字符串?

javascript - 在圣诞节调用函数

javascript - JavaScript 支持多线程吗?如果没有,我应该如何实现 sleep()?

angularjs - 将 SignalR 与 AngularJs 集成

c++ - 通过数组移动指针 - 通过引用或递增传递?