2014-05-01 49 views
0

我想用角度js编写时间跟踪器。 我旁边HTML代码Angular JS更新ng-repeat

  <tr ng-repeat="task in tasks"> 
       <td>1</td> 
       <td>{{task.name}}</td> 
       <td class="text-right">{{task.time}}</td> 
      </tr> 

我有模型任务

function Task(name, time) { 
     this.name = name; 
     this.time = time; 

     this.incrementTime = function($scope) { 
      this.time++; 
     } 
    } 

所以我想更新任务每秒钟在控制器 像这样

function TaskController($scope, $interval) { 
    $scope.tasks = []; 

    $scope.addTask = function() { 
     var task = new Task($scope.task, 0); 
     $interval(task.incrementTime, 1000); 
     $scope.tasks.unshift(task); 
     $scope.task = ''; 
    } 
} 

但我的表不更新任务

回答

0

由于Gruffy Bunny提到过,您应该使用$ interval而不是setInterval。 $ interval是setInterval的一个包装,但是基本的事情是$ interval做了setInterval没有做的事情,用$ scope.apply(yourCallback)封装了回调调用,它启动了一个摘要循环,它会检查你的作用域模型并最终会更新你的观点。

+0

http://plnkr.co/edit/ ?p = streamer&s = GYw5zvmCIPpQoxHC –

+0

1.您不需要表单和ng-submit,只需使用ng-click即可。 2.你正在使用旧版本的角度,没有$间隔,使用最新版本。 – haimlit

+0

谢谢,它的工作原理 –

0

你正在设置var task作为新的任务,而不是更新现有的任务。像$scope.task.incrementTime()东西是你想要

+0

但是我有模型任务 函数任务(名称,时间){...} –

+0

您正在创建一个新的Task对象并改变它,而不是像你想要的那样改变$ scope.task。如果你想使用'新任务',你需要添加这个新的'任务'对象''scope.tasks' – SnareHanger

+0

是的,我添加了$ scope.tasks.unshift(任务),但表仍然没有更新,如果我改变了时间 –

1

使用$interval服务并通过incrementTime功能区间

function TaskController($scope, $interval) { 
    $scope.tasks = [] 

    $scope.addTask = function() { 
    //add task 
    var task = new Task($scope.task, 0); 
    $interval(task.incrementTime, 1000); 
    $scope.tasks.push(task); 
    } 
} 

和调整的任务建构,使得incrementTime引用了正确的时间变量是什么:

function Task(name, time) { 
    var self = this; 

    this.name = name; 
    this.time = time; 

    this.incrementTime = function() { 
     self.time++; 
    } 
} 

Fiddle

+0

它仍然没有为我工作 http://plnkr.co/edit/?p=streamer&s=GYw5zvmCIPpQoxHC –

+0

小提琴的作品 - 蹲式incrementTime使用了错误的'这' –