使用下拉列表过滤 ng 重复,而不复制下拉选项

Filter ng-repeat with dropdown without duplicating the dropdown options

本文关键字:复制 选项 下拉列表 过滤 ng 重复      更新时间:2023-09-26

同样,我可以在ng-repeat中手动执行filter: { category : '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'添加到模块依赖项中:

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

见小提琴

注意:本身不是问题,但我从<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();
})