0

我用 AngularJS 创建了一种词汇表

当我单击字母列表按钮时,一个函数 (categoryFilterFn) 按类别过滤 json 数据。当过滤器没有返回结果时,我想将 CSS 应用于按钮。例如,如果我单击 Z 按钮,json 文件中不存在相关条目,因此过滤器不返回任何内容,并且 Z 字母按钮将设置为带有 css 的白色。我不知道如何使用 ng-clas 来应用它。这里的代码:

<div ng-app="essaiApp">
  <section ng-controller="EssaiCtrl">
    <button type="button" ng-repeat="letter in alphabet" ng-click="selectCategory(letter)">
      {{letter}}
    </button>
    <div ng-repeat="item in todo.items | filter:categoryFilterFn">
      {{item.categoria}}
    </div>
  </section>
</div>

控制器:

essaiApp.controller("EssaiCtrl", function ($scope, $filter) {
    $scope.todo = model;
    var selectedCategory = null;

    $scope.selectCategory = function (newCategory) {
        selectedCategory = newCategory;
    }

    $scope.categoryFilterFn = function (polo) {
        return selectedCategory == null ||
            polo.categoria == selectedCategory;
    }

    $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
});
4

2 回答 2

2

保存过滤结果:

<div ng-repeat="item in filteredItems = ( todo.items | filter:categoryFilterFn)">

移至:selectedCategory_$scope

$scope.selectedCategory = null;

$scope.selectCategory = function(newCategory) {
  $scope.selectedCategory = newCategory;
}

ng-class在按钮上使用:

ng-class="{ 'no-result': selectedCategory === letter && !filteredItems.length }"

演示: http ://plnkr.co/edit/Gl1i4dLyCCwuorQHB5SS?p=preview

于 2014-05-21T05:48:41.007 回答
2

作为 tasseKatt 解决方案的替代方案,您可以在控制器中管理过滤后的数组:

$scope.selectCategory = function(newCategory) {
  $scope.filtered = [];
  $scope.selectedCategory = newCategory;
}

$scope.categoryFilterFn = function(item) {
  if (item == $scope.selectedCategory)
    $scope.filtered.push(item);

  return item == $scope.selectedCategory
}

http://plnkr.co/edit/oOSOGPjaq9g7DaWRaFks?p=preview

于 2014-05-21T06:00:24.343 回答