如何在ng-repeat间隔中在数组中应用新添加的对象?

时间:2015-03-05 13:02:48

标签: javascript angularjs intervals

假设以下场景:首先单击cont!按钮,然后单击add!,如何应用计算函数中新推送的对象在数组中,以便它在ng-repeat中显示为最后一个?

更新了工作示例:



var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $interval) {
  $scope.tabs = [{
    name: "one",
    active: true
  }, {
    name: "two",
    active: false
  }, {
    name: "three",
    active: false
  }];
  $scope.add = function() {
    $scope.tabs.push({
      name: "display me in the counter",
      active: false
    });
  };
  $scope.count = function() {
    var i = 0;
    var interval;

    $interval.cancel(interval);
    interval = $interval(function() {

      i = i % $scope.tabs.length;
      $scope.tabs[i].active = false;
      i++
      $scope.tabs[i].active = true;
      console.log($scope.tabs.length, i)
      if (!($scope.tabs.length - 1 > i)) $interval.cancel(interval);
    }, 2000);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<div ng-app="app">
  <div ng-controller="homeCtrl">
    {{tabs}}
    <br>
    <button ng-click="add()" class="btn btn-default">add!</button>

    <button ng-click="count()" class="btn btn-default">count!</button>

    <div ng-repeat="no in tabs" ng-show="no.active" ng-bind="no.name">
    </div>

  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

目前,当您调用$scope.tabs.length服务时,您正在兑现$interval

如果要显示在调用count后添加的项目,则必须在间隔函数中检查数组长度,如:

interval = $interval(function() {
  if ($scope.tabs.length-1 > i) {
   ...
  } else {
   $interval.cancel(interval);
  }

}, 2000);