使用ng-model按键(key,val)对过滤

时间:2016-04-25 06:27:59

标签: javascript angularjs angular-ngmodel angularjs-ng-model

我有以下数据:

[
  {
    "rub": {
      "item1": 979,
      "item2": 32,
      "item3": 845
    },
    "shop": "shop1",
  },
  {
    "rub": {
      "item232": 84,
      "item213": 348
    },
    "shop": "shop2"
  }
]

我尝试使用ng-model按键在表格中对其进行过滤。但它根本没有过滤。

<table class="table ng-cloak" ng-repeat="rub in rubs | filter:isActive" ng-if='isActive'>
  <input type="text" class="form-control" placeholder="Товар" ng-model="rub.rub[key]">
    <thead>
      <tr>
        <th>#</th>
        <th>Товар</th>
        <th>Число</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat='(key, val) in rub.rub'>
        <td>{{ $index }}</td>
        <td>{{ key }}</td>
        <td>{{ val }}</td>
      </tr>                  
    </tbody>
  </table>

我的控制器:

curryControllers.controller('CurryRubricsCtrl', ['$scope', '$routeParams', '$http', '$route',
  function($scope, $routeParams, $http, $route) {
    $scope.cityId = $routeParams.cityId;
    $http.get('cities.json').success(function(data) {
      $scope.cities = data;
    $http.get('json/shop_data.json').success(function(data2) {
      $scope.rubs = data2;

      $scope.isActive = function(item) {
    return item.shop === $scope.cityId;
  };
  });
  });

我尝试将$scope.searchRub = ''添加到控制器并在html模板中放置一个表单。

  <form>
    <div class="form-group">
      <div class="input-group">
        <div class="input-group-addon"><i class="fa fa-search"></i></div>

        <input type="text" class="form-control" placeholder="Поиск" ng-model="searchRub">

      </div>      
    </div>
  </form>

在此处添加了此“searchRub”过滤器:<td> {{ key | filter:searchRub }} </td> 它也没有帮助。

2 个答案:

答案 0 :(得分:1)

You want the search box to model an independent value which you can then use to filter, rather than trying to model it to the key of an object that you are already using.

<input type="text" class="form-control" placeholder="Товар" ng-model="search”>

There are a number of ways to use this value to filter, but the easiest is with an ng-show:

<tr ng-repeat='(key, val) in rub.rub' ng-show="search ? search===key : true">

Here’s the plunk. I’ve hardcoded the cityId to avoid using routeParams for the demo.

https://plnkr.co/edit/sI8HAbNKBBJGMx0FediD?p=preview

type "item1" into the search box.

答案 1 :(得分:0)

您可以使用Underscore.js实现此目的,

data = [
  {
    "rub": {
      "item1": 979,
      "item2": 32,
      "item3": 845
    },
    "shop": "shop1"
  },
  {
    "rub": {
      "item232": 84,
      "item213": 348
    },
    "shop": "shop2"
  }
]
$scope.specific_key = []
_.filter(data, function(val){$scope.specific_key.push(val['rub'])});
console.log($scope.specific_key); 

$scope.specific_key中,它将返回包含键'rub'。