【问题标题】:How to dynamic count how many times ng-repeat repeated?如何动态计算 ng-repeat 重复的次数?
【发布时间】:2023-03-29 04:51:01
【问题描述】:

关于如何正确计算视图中重复记录的快速问题?

这里是视图:

<h4> Drafts </h4>
<ul class="nav nav-pills scrollable-nav">
  <li ng-repeat="solution in solutions | filter: {'username': username}: true | filter: {visible: false} "> 

    <a href="#" onclick="return false;">
      <h5 ng-click="editSolution(solution.$id)">{{solution.name}}</h5>
    </a>

  </li>                            
</ul>

我想知道解决方案重复了多少次?用户可以随时将 solution.visible 值更改为 true,因此我需要动态显示该数字。

我可以使用范围内的变量来跟踪该数字,但我想知道是否有其他更好的方法可以做到这一点?

【问题讨论】:

    标签: angularjs data-binding angularjs-ng-repeat ng-repeat angularjs-filter


    【解决方案1】:

    您可以创建一个临时变量来保存过滤结果的值

    <li ng-repeat="solution in filteredSolutions = (solutions | filter: {'username': username, visible: false}: true)">
    

    然后{{filteredSolutions.length}} 得到计数

    您还可以使用其他方法,如@Claies 建议的那样对过滤结果进行别名,这在 Angular 1.3+ 中受支持

    <li ng-repeat="solution in solutions | filter: {'username': username, visible: false}: true as filteredSolutions">
    

    【讨论】:

    • 在 Angular 1.3+ 中的替代方法是使用来自ng-repeat 微语法的内置别名as alias 表达式,即&lt;li ng-repeat="solution in solutions | filter: {'username': username, visible: false}: true as filteredSolutions"&gt;
    • @Claies 哦..很好,这确实使代码可读..我已经更新了答案。谢谢:)
    • 谢谢你们!我用了 Claies 的方法,效果很好!
    • @Lisa 很高兴知道这一点。谢谢:)
    【解决方案2】:

    有时在控制器中过滤数据更方便。 你可以这样做:

    <div ng-controller="ListCtrl as ctrl">
          <ul>
              <li ng-repeat="person in ctrl.people" ng-click="ctrl.hide(person)">
                {{person.name}}: {{person.phone}}
              </li>
          </ul>
          <div>
              Records count: {{ctrl.people.length}}
          </div>
    </div>
    

    和控制器:

    app.controller('ListCtrl', ['$scope', '$filter', function ($scope, $filter) {
        var self = this;    
        this.hide = function(item) {
           item.visible = false;
           self.refresh();
        };    
        this.refresh = function() {
            self.people = $filter('filter')(people, {visible: true});
        };   
        this.refresh();
    }]);
    

    这样您就可以在控制器变量中获得过滤后的数据,并可以使用它来显示记录数。

    这里是jsfiddle with demo

    【讨论】:

    • 感谢您的演示!有用!但这次我使用了简单的修复方法。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2015-07-22
    • 1970-01-01
    相关资源
    最近更新 更多