【问题标题】:AngularJS limitTo: 4 counts element which shouldn't be displayedAngularJS limitTo: 4 counts 不应该显示的元素
【发布时间】:2017-09-18 13:03:33
【问题描述】:

我的过滤器有问题。我有一个 JSON 数据,我想在我的网站上显示 4 个过滤元素。它看起来像这样:

<div ng-repeat="place in places | limitTo: 4 | filter: {cheap: 'true'}" class="col-lg-3">

所以,我只想在元素具有“cheap = true”时显示它。我的问题是 JSON 中的第一个元素具有“cheap = false”,而我的 ng-repeat 仅显示 3 个项目而不是 4 个。我认为它从数据的开头开始计数并以 4 个元素结束,所以如果元素 1 便宜是假的只显示接下来的 3 个是真的。

我怎样才能做出类似“如果元素 1 便宜是假的,跳过它并显示接下来的 4 个元素,它们是真的”。

我希望你明白我的意思。感谢您的帮助!

【问题讨论】:

  • 您是否尝试将limitTo 放在filter 之后?就像&lt;div ng-repeat="place in places | filter: {cheap: 'true'} | limitTo: 4" class="col-lg-3"&gt;
  • 您将结果限制为 4,然后过滤这 4 个,返回一个子集。如果可能的话,尝试颠倒limitTofilter 的顺序。
  • 哇,这太容易了。这是正确的答案谢谢!

标签: javascript angularjs json angularjs-ng-repeat filtering


【解决方案1】:

根据 cmets 的解决方案,这非常简单 - 我必须切换顺序并将“filter:”放在首位,而不是“limitTo:”。谢谢!

【讨论】:

    【解决方案2】:

    只需将limitTo 放在filter 之后

    var myApp = angular.module('myApp', []);
    
    
    function MyCtrl($scope) {
      $scope.places = [{
        cheap: true
      }, {
        cheap: true
      }, {
        cheap: false
      }, {
        cheap: true
      }, {
        cheap: true
      }, {
        cheap: true
      }, {
        cheap: true
      }, ]
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp">
      <div ng-controller="MyCtrl">
        <h1>Good</h1>
        <div ng-repeat="place in places  | filter: {cheap: 'true'} | limitTo: 4" class="col-lg-3">
          {{place.cheap}}
        </div>
    
        <h1>Bad</h1>
        <div ng-repeat="place in places| limitTo: 4  | filter: {cheap: 'true'} " class="col-lg-3">
          {{place.cheap}}
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-20
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      相关资源
      最近更新 更多