ng重复中的角度过滤器

时间:2016-03-01 15:50:17

标签: angularjs filter

我有一个过滤器,当我的表中只有一行时可以正常工作。但是当我有多行时如何过滤特定行(索引)?在此示例中,我想按国家/地区ID过滤以显示特定城市:

我的Html:

 <tr ng-repeat="country in countries">
     <select ng-model="country.id" ng-change="selectCountry($index,country.id)"
                                            ng-options="country.id as country.name for country in countries">
                                        <option value="">Country</option>
                                    </select>

    <select ng-model="city.id" ng-change="selectCity($index,city.id)"
                                            ng-options="city.id as city.name for city in cities" | filter:filterByCities>
                                        <option value="">City</option>
                                    </select>
</tr>

Ng-Controller:

$scope.countries = {
     {"id" : 1, "name" : "USA" },
     {"id" : 2, "name" : "CANADA" }
 }

 $scope.cities= {
     {"id" : 1, "name" : "MIAMI" },
     {"id" : 2, "name" : "TORONTO" }
 }


$scope.selectCountry = function (index, value) {

                if (value ==1) {
                    $scope.selectedCities = [1, 2];
                }
                else if (value == 2) {
                    $scope.selectedCities = [3, 4];
                }
                $scope.filterByCities = function (type) {
                    return ($scope.selectedCities.indexOf(type.id,index) !== -1);
                };
            }

但是过滤器适用于我表格中的所有行,不仅适用于我选择过滤器的行。

谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

你的代码没有多大意义。我建议你改变那里你有第三个数组,对应你的行模型。

您不希望所有行的selectedCities都相同。表格中的每个输入城市都应按同一行国家/地区的输入进行过滤。您需要一个模型来跟踪这些更改,这是rows数组的目标:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.rows = [{
      countryId : 4, cityId : 2 
  }, {}, {}];

  $scope.countries = [{
    "id": 1,
    "name": "USA"
  }, {
    "id": 4,
    "name": "CANADA"
  }];

  $scope.cities = [{
    "id": 1,
    "name": "MIAMI",
    "countryId": 1
  }, {
    "id": 2,
    "name": "VANCOUVER",
    "countryId": 4
  }, {
    "id": 3,
    "name": "TORONTO",
    "countryId": 4
  },{
    "id": 1,
    "name": "LOS ANGELES",
    "countryId": 1
  }];
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<!DOCTYPE html>
<html ng-app="plunker">
<body ng-controller="MainCtrl">
  <table>
    <tr>
      <th>
        Country
      </th>
      <th>
        City
      </th>
    </tr>
    <tr ng-repeat="row in rows">
      <td>
        <select ng-model="row.countryId" ng-options="country.id as country.name for country in countries">
          <option value="">Country</option>
        </select>
      </td>
      <td>
        <select ng-model="row.cityId" ng-options="city.id as city.name for city in cities | filter:{countryId:row.countryId}">
          <option value="">City</option>
        </select>
      </td>
    </tr>
    <table>
</body>
</html>