Search code examples
javascriptangularjsarraysangularjs-filter

Filtering out in for loop


I'm trying to create a drop down list and when I am creating it I want to filter by a field. For example:

    <!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>

How would I filter by difficulty in this example? Is it possible to do something like

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

Solution

  • Use a custom filter like this:

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

    and apply it in ng-options like this:

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

    Demo below:

    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>