与元素匹配并获取结果的角度js

时间:2016-10-22 10:08:07

标签: html angularjs json

如果item匹配Array元素,则过滤结果 具有以下json结构

  [{"id": "1", "name":"product1","items": ["item1","item2"],},
  {"id": "2", "name":"product2","items": ["item4","item3"],},
  {"id": "3", "name":"product3","items": ["item5","item1"],}]

要求是如果我从下拉列表中选择item1,我需要过滤包含item1的整个对象。 我是棱角分明的新手,任何人都可以帮助我

2 个答案:

答案 0 :(得分:1)

filter

中使用ng-repeat

通过文本框

Search by item: <input type="text" ng-model="search.items">
<div ng-repeat="product in data | filter:search">
  {{product}}
</div>

通过下拉列表

<select class="form-control" ng-model="selectedThana" ng-options="t.items for t in data">
    <option value="">Select</option>
</select>
<div ng-repeat="product in data | filter:selectedThana">
  {{product}}
</div>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.data = [{"id": "1", "name":"product1","items": ["item1","item2"],},
  {"id": "2", "name":"product2","items": ["item4","item3"],},
  {"id": "3", "name":"product3","items": ["item5","item1"],}];
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
  <select class="form-control" ng-model="selectedThana" ng-options="t.items for t in data">
                        <option value="">Select</option>
                    </select>
<div ng-repeat="product in data | filter:selectedThana">
  {{product}}
</div>
</body>

答案 1 :(得分:0)

您可以使用$ filter,

执行此操作

<强> HTML

<select ng-model="user" ng-change="getselected(user)" ng-options="code.name as code.name for code in optionsdownload">
</select>

<强>控制器

 $scope.getselected = function(item){
    $scope.wholeobj = $filter("filter")($scope.optionsdownload, item);
 }

<强> DEMO