【问题标题】:AngularJS: Apply a css class when a filter return no resultAngularJS:当过滤器没有返回结果时应用css类
【发布时间】:2014-07-09 13:52:15
【问题描述】:

我用 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("");
});

【问题讨论】:

  • 可以发model的内容吗

标签: css angularjs ng-class


【解决方案1】:

作为 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

【讨论】:

  • 感谢您的选择,我会冷静地学习和应用您的代码。它帮助我更好地理解 AngularJS。
  • +1 好调用,当控制器中已经定义了自定义过滤函数时首选
【解决方案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

【讨论】:

  • 非常感谢您的回答,一切正常。我还是 AngularJS 的新手,你的代码帮助我更好地理解 ng-class。
猜你喜欢
  • 2017-01-15
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多