使用下拉菜单过滤 ng-repeat 而不复制下拉选项

Filter ng-repeat with dropdown without duplicating the dropdown options

同样,我可以在ng-repeat中手动执行filter: { category : 'Popular'},我希望能够对下拉菜单执行相同的操作。

我能够使基础知识发挥作用。我有两个问题:我不希望下拉列表中的类别重复,我希望当我在下拉列表中 select "Popular" 时能够看到分类为 "Popular" 的所有内容.

这是我的HTML:

<div ng-controller="SuperCtrl" class="row">
  <ul class="small-12 medium-12 columns">
    <select ng-model="find" ng-options="entry.category for entry in parsedEntries"><option value="">Select Category</option></select>.
    <li ng-repeat="entry in parsedEntries | filter: find">
      <strong>{{ entry.title }} </strong><br>
      {{ entry.description }}
   </li>
 </ul></div>

这是控制器:

app.controller('SuperCtrl', ['$scope', '$http', function($scope,$http) {
var url = 'https://spreadsheets.google.com/feeds/list/1lZWwacSVxTD_ciOsuNsrzeMTNAl0Dj8SOrbaMqPKM7U/od6/public/values?alt=json'
var parse = function(entry) {
  var category = entry['gsx$category']['$t'];
  var description = entry['gsx$description']['$t'];
  var title = entry['gsx$title']['$t'];
  return {
    category: category,
    description: description,
    title: title
  };
}
$http.get(url)
.success(function(response) {
  var entries = response['feed']['entry'];
  $scope.parsedEntries = [];
  for (key in entries) {
    var content = entries[key];
    $scope.parsedEntries.push(parse(content));
  }
});
}]);

让它按你想要的方式工作:

<select ng-model="find" ng-options="entry.category as entry.category for entry in parsedEntries | unique: 'category'">

unique 过滤器来自 angular-filter。它需要将 'angular.filter' 添加到您的模块依赖项中:

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

fiddle

注意:这本身不是问题,但我从 <ul> 元素中取出了 <select> 元素。

只需将唯一类别放入名为 categories 的字符串数组中,对数组进行排序,然后使用 ng-options:

显示它
<select ng-model="find" ng-options="category as category for category in categories"><option value="">Select Category</option></select>.

在您的解析函数之后将其附加到您的代码中,并删除您拥有的 $http.get。这定义了一个 contains 函数并在对象返回的同时构建数组:

function contains(a, obj) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
};

$http.get(url)
.success(function(response) {
  var entries = response['feed']['entry'];
  $scope.parsedEntries = [];
  $scope.categories = [];
  for (key in entries) {
    var content = entries[key];
    var obj = parse(content);
    $scope.parsedEntries.push(obj);

    if (!contains($scope.categories, obj.category))
    {
      $scope.categories.push(obj.category);
    }
  }

  $scope.categories.sort();
})