Angularjs:ng-repeat工作时如何显示增量计数器(进度消息)?

时间:2016-10-17 12:42:37

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

要求

假设我有一个10000长度的数组。虽然ng-repeat正在重复并显示列表的内容,但同时我需要显示一条进度消息,显示已创建的元素数量。

长话短说显示进度消息,显示ng-repeat已到达的距离

我做了什么

这是我已完成的代码(不工作)。

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

app.controller('appCtrl', function ($scope, $timeout) {

    $scope.list = []; /// list that is going to be repeated
    $scope.count = 10000; /// no of items in the list


    /// filling the list
    var templist = [];
    for (var index = 0; index < $scope.count; index++) {

        templist.push(index);
    }
    $scope.list = templist;

    ///  default msg of progress
    var progress = '0/' + $scope.count;

    /// function will be called when the the list will be getting rendered
    $scope.reportProgress = function (i) {
        console.log(i);
        setTimeout(function () {
            /// updating the progress message
            progress = i + "/" + $scope.count;
            $("#prog").html(progress);
        }, 1);
    }

})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>
    <div ng-app="app" ng-controller="appCtrl">

        progress: <span id="prog"></span>

        <div ng-repeat="i in list track by $index">
            {{i}} {{reportProgress($index)}}
            <hr/>
        </div>
    </div>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

在您的HTML中,您可以使用以下内容:ng-if="showProgress(i)"

<div ng-repeat="i in list track by $index">
   <div ng-if="showProgressBar(i)">
        <!-- progress bar for each {{item}} -->
   </div>
 </div>

在您的范围内,您可以传递id或其他value

$scope.showProgressBar = function(i){
      $scope.list.forEach(function(item){
          if (item._id === i.id){
            item.progress = !item.progress;
          }
      });
};

答案 1 :(得分:0)

<!--PROBLEMATIC CODE -->

<div ng-repeat="i in list track by $index">
    {{i}} {{reportProgress($index)}}
    <hr/>
</div>

使用此代码的探测器是在每个摘要周期中,列表中的每个项目都将报告进度。

而是在自定义指令的链接函数中嵌入reportProgress调用。

<div ng-repeat="i in list track by $index">
    {{i}}
    <hr report-expn="reportProgress($index)" />
</div>

JS

app.directive("reportExpn", function () {
    return {
        link: function(scope,elem, attrs) {
            scope.$eval(attrs.reportExpn);
        }
    };
});

这样,当链接reportProgress指令时,每个列表项只会调用report-expn函数一次。