2016-04-25 43 views
0

我ahave以下数据:通过在(键,val)的一对键过滤器使用纳克 - 模型

[ 
    { 
    "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> 它没有帮助。

+0

您的对象中没有“链接”键,因此它总是会返回false \ –

+0

@Devidas,对不起,我编辑了我的文章 –

回答

1

您希望搜索框为您可以用来过滤的独立值建模,而不是尝试将其建模为您已使用的对象的键。

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

有许多的方式来使用这个值来过滤,但最简单的是用NG-显示:

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

这里的普拉克。我硬编码了cityId以避免使用routeParams进行演示。

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

型 “物品1” 在搜索框中。

+0

谢谢。几乎。但是当输入为空时它什么都不显示。如果输入字段为空,如何显示所有表行? –

+1

如果搜索为空,您希望将ng-show默认为true。我已经更新了答案和Plunk。 –

+0

@GerainAnderson,谢谢!有没有一种方法可以动态过滤数据,而不会在输入字段中完全匹配。我的意思是,如果用户动态地写'ite'数据过滤器。 –

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,它会返回包含键 '蹭'。

+0

我应该在我的'ng_model'中传递'specific_key'输入标签? –

+0

你的ng模型让我困惑......从你的ng模型中,根据你的ng-repeat和你的对象,rub.rub [key]不能给你想要的东西......清楚你想要在你的模型中做什么?我明白你的表中你真正想要的是什么......清楚ng-model –

+0

你也可以根据你的数据将specific_key'rub'传递给你的ng模型,它应该是ng-model ='rub [your_key]' –