【问题标题】:setInterval function does not change the $scope in the viewsetInterval 函数不会改变视图中的 $scope
【发布时间】:2016-05-11 06:49:12
【问题描述】:

我在客户端有一个带有角度 js 和 html 的 spring 应用程序,我想每 6 秒更新一次视图中的信息,因为我调用了 setInterval 函数,但它不会改变视图 这是我的代码

$scope.aat=function(){
                $http.get("http://localhost:8080/projet/getInspectionEnCoursDinspection")
    .success(function (data) {

     $scope.tab1=data;
     console.log("size="+ $scope.inspectionEnCoursDinspection1.length);

   })   
} ,

setInterval(function(){ $scope.aat() },60000);

这是我的html视图

<table class="table table-bordered">
<tr ng-repeat="insp in tab1">
<td>Mat{{insp.vehicule.matricule}}

<div ng-repeat="aa in insp.tests">
Test<ul><li ng-repeat="defaut in aa.defauts">{{defaut.nomDefaut}}</li></ul>
</div>

</td>

<td><button ng-click="annulerTest()"
                                    class="btn btn-default btnt">
                                    <i class="glyphicon glyphicon-remove"></i>
                                </button></td>
</tr>
</table>

任何帮助将不胜感激

【问题讨论】:

  • 60000ms 是每分钟,而不是每 6 秒。
  • 尝试使用 $scope.apply 到 $scope.aat 告诉 Angular 将更改注册到您的数组。
  • 好的,谢谢@Bergi,但这不是问题,视图不会改变,只是我刷新了页面
  • $scope.aat=function(){ $http.get("http://localhost:8080/projet/getInspectionEnCoursDinspection") .success(function (data) { $scope.tab1=data; console.log("size="+ $scope.inspectionEnCoursDinspection1.length); $scope.apply(); }) }
  • 你应该尝试使用 Angular 的 $interval 而不是 plainJS 'SetInterval'。除非您手动$scope.apply()

标签: javascript angularjs


【解决方案1】:

相关:angular doesn't apply changes to array(remove item on socket event)

这是因为您使用 setInterval 来修改 $scope.tab1 和 $scope.aat。

使用任何非 Angular 代码来修改您的数据将使您的视图不同步,因为 Angular 不知道更改(它没有完成工作,所以它不会知道)。

您可以通过使用 Angular 的 $interval 而不是 setInterval 来重复您的更新来解决此问题。或者在$scope.aat 中添加$scope.apply() 以告诉Angular 重新检查所有更改。

在这种情况下最好使用 $interval。 $scope.apply() 应该是最后的手段。

$scope.aat=function(){
                $http.get("http://localhost:8080/projet/getInspectionEnCoursDinspection")
    .success(function (data) {

     $scope.tab1=data;
     console.log("size="+ $scope.inspectionEnCoursDinspection1.length);
     //this--->$scope.apply();
   })   
} ,

//OR this-->$interval(function(){ $scope.aat() },60000);

【讨论】:

  • $interval... 我尝试仅在没有角度替代方案时使用 .apply()。
  • @Tyler 同意,只是让 OP 知道他或她的选择
  • 干杯。 .apply() 的解释对于其他无法使用内置函数的情况很有用。
猜你喜欢
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多