angularjs中的变量未更新

时间:2016-01-03 20:18:20

标签: javascript angularjs setinterval angular-digest

我尝试使用AngularJs创建一个计时器,但是当我在setInterval方法中增加timerCount时,值会更改,但视图不会使用新值更新。 当我检查控制台日志时,我发现timerCount按预期递增,如果我再次单击该按钮,则timerCount将获取视图中的当前值。 如何每秒更改视图?

这是html:

<p>timer count: {{timerCount}}</p>
  <button ng-click="startTimer()">start timer</button>

和控制器:

var app=angular.module('examApp',[]);
    app.controller('examCtrl',function($scope){

        $scope.timerCount=0;
        $scope.startTimer=function(){
            setInterval(function(){
                console.log($scope.timerCount);
                $scope.timerCount++;
            },1000)
        }
    })

http://plnkr.co/edit/CScdb8QFSFpKR7WJWuQJ?p=preview

2 个答案:

答案 0 :(得分:2)

在角度上下文之外更新角度范围1>------Build started : Project : Project5, Configuration : Debug Win32------ 1> Source.cpp 1>c:\users\radek\documents\visual studio 2013\projects\project5\project5\source.cpp(29) : error C2280 : 'std::unique_ptr<Neighbour,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function 1> with 1>[ 1> _Ty = Neighbour 1>] 1> c:\program files(x86)\microsoft visual studio 12.0\vc\include\memory(1487) : see declaration of 'std::unique_ptr<Neighbour,std::default_delete<_Ty>>::operator =' 1> with 1>[ 1> _Ty = Neighbour 1>] 1> This diagnostic occurred in the compiler generated function 'std::array<std::unique_ptr<Neighbour,std::default_delete<_Ty>>,12> &std::array<std::unique_ptr<_Ty,std::default_delete<_Ty>>,12>::operator =(const std::array<std::unique_ptr<_Ty,std::default_delete<_Ty>>,12> &)' 1> with 1>[ 1> _Ty = Neighbour 1>] == == == == == Build: 0 succeeded, 1 failed, 0 up - to - date, 0 skipped == == == == == 的任何函数都不会使用角度来运行摘要周期,从而导致绑定不会在HTML上得到更新。

这里使用variable/bindings(这不会启动角度来运行摘要周期),这是异步运行的本机JavaScript函数,并且您正在尝试从此函数更新范围值。您应该使用setInterval而不是$interval

基本上setInterval服务在内部使用$interval,但回调函数已包含在setInterval内,并在每个时间间隔为您运行摘要周期。

<强>代码

$rootScope.$evalAsync

Demo Plunkr

答案 1 :(得分:0)

使用Pankaj的回答你也可以使用它,因为当使用纯js和Angular你需要使用 $ apply 方法,如

$scope.startTimer=function(){
        setInterval(function(){
            console.log($scope.timerCount);
            $scope.timerCount++;
            $scope.$apply();
        },1000)
    }

然后它将按预期工作。

相关问题