使用 ng 模型按键入(键,值)对过滤

Filter by key in (key, val) pair using ng-model

本文关键字:过滤 ng 模型 使用      更新时间:2023-09-26

我有以下数据:

[
  {
    "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>

在这里添加了这个"搜索Rub"过滤器:<td> {{ key | filter:searchRub }} </td>这也无济于事。

您希望搜索框对一个独立的值进行建模,然后可以使用该值进行筛选,而不是尝试将其建模为已在使用的对象的键。

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

方法可以使用此值进行筛选,但最简单的方法是使用 ng-show:

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

这是扑通。 我已经对cityId进行了硬编码,以避免在演示中使用routeParams。

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

在搜索框中键入"item1"。

您可以使用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'。