【问题标题】:Incrementing Variable in Interval breaks Data Binding在间隔中递增变量会中断数据绑定
【发布时间】:2016-12-12 05:59:36
【问题描述】:

我所做的只是在一个区间内增加一个数字。这一直有效到 600,然后视图停止更新(变量仍在后台更新)。如果我将间隔时间减少到 500,则增量值会上升到 1200,这让我认为它与时间相关导致了这种行为。实际变量不断增加,但绑定中断并且视图没有得到更新。

app.controller('testCtrl', function($state, $scope, $cordovaSQLite,  $filter, $timeout,$ionicHistory){

setInterval(function(){

      $scope.u_stepCount += 200;
      console.log( $scope.u_stepCount );
    }, 1000);

});


<ion-view title="Test">
 <ion-content class="dashboard-background">
   <p id="steps">{{u_stepCount}}</p>
   <p id="test_steps"></p>
  </ion-content>  

</ion-view>

【问题讨论】:

    标签: angularjs data-binding


    【解决方案1】:

    有几件事

    1. 您应该使用$interval 服务而不是setInterval,它会在每次调用函数回调后负责运行摘要。
    2. 在将ng-model 定义为ion-content directive create a prototypically inherited child scope 时,请遵循Dot rule。像$scope.model = { u_stepCount: 0 } OR else 你可以在定义控制器时使用控制器作为模式。您将从控制器中删除 $scope 并将 this(context) 暴露给视图绑定。

    总的来说,您的代码更改将如下所示。

    HTML

    <ion-view title="Test">
     <ion-content class="dashboard-background">
       <p id="steps">{{model.u_stepCount}}</p>
       <p id="test_steps"></p>
      </ion-content>  
    </ion-view>
    

    代码

    //removing other dependency that you had just to make code cleaner
    //you can have it there if you needed in your actual codebase
    app.controller('testCtrl', function($state, $scope, $interval){ //<-inject $interval here
        $scope.model = { u_stepCount: 0 };
        $interval(function(){
          $scope.model.u_stepCount += 200 ;
          console.log( $scope.u_stepCount );
        }, 1000);
    });
    

    【讨论】:

      【解决方案2】:

      要达到预期的效果,请使用 $scope.apply

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

      http://codepen.io/nagasai/pen/zBmLmj

      获得相同结果的推荐方法是使用 $interval

      JS:

      var app = angular.module('myApp', []);
      app.controller('myCtrl', function($scope,$interval) {
        $scope.u_stepCount=0;
      $interval(function(){
             $scope.u_stepCount += 200;
             console.log( $scope.u_stepCount );
      
          }, 1000);
      
      });
      

      http://codepen.io/nagasai/pen/rLqAQG

      【讨论】:

      • 是的 Pankaj,我只是为了让 OP 帖子正常工作并使用推荐的最佳方法进行更新 :) 谢谢 Pankaj
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2018-11-07
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多