最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - scope variable updated in angular but change is not reflected to user - Stack Overflow

programmeradmin2浏览0评论

I have some angular variables set like so:

$scope.pane = [];
$scope.pane.count = 0;
$scope.pane.max = 5;

Then I display the variables in the HTML like this:

{{pane.count}}

This works fine and displays 0 as expected.

Now if I update the variable at any point, the update does happen (I can see using console.log) but the printed version in the HTML does not update.

E.g.

setTimeout(function(){
  $scope.pane.count = 1;
},1000);

I am using Angular v1.3. What am I doing wrong?

I have some angular variables set like so:

$scope.pane = [];
$scope.pane.count = 0;
$scope.pane.max = 5;

Then I display the variables in the HTML like this:

{{pane.count}}

This works fine and displays 0 as expected.

Now if I update the variable at any point, the update does happen (I can see using console.log) but the printed version in the HTML does not update.

E.g.

setTimeout(function(){
  $scope.pane.count = 1;
},1000);

I am using Angular v1.3. What am I doing wrong?

Share Improve this question asked Nov 11, 2014 at 13:48 CaribouCodeCaribouCode 14.4k33 gold badges111 silver badges183 bronze badges 1
  • 1 Your pane should need to be {} object instead of array. – Rahil Wazir Commented Nov 11, 2014 at 13:54
Add a comment  | 

2 Answers 2

Reset to default 15

In order to let angular know about changes, you have to use angular wrapper for timeout.

Try this:

$timeout(function() {
  $scope.pane.count = 1;
}, 1000);

Generally, when you have a structure outside angular world(such as jQuery plugin) that changes values, you have to call $scope.$apply() to let angular know about them.

$scope.$apply();

setTimeout is outside angularjs scope so you need to use $scope.$apply or $timout please see sample demo below

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope, $timeout) {

  $scope.pane = [];
  $scope.pane.count = 0;
  $scope.pane.count2 = 0;
  $scope.pane.max = 5;

  setTimeout(function() {
    $scope.$apply(function() {
      $scope.pane.count = 1;
    })

  }, 1000);

  $timeout(function() {
    $scope.pane.count2 = 5;
  }, 2000);


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app">
  <div ng-controller="homeCtrl">
<h3>setTimeout</h3>
    Count 1: {{pane.count}}<br/>
    <h3>$timeout</h3>
    Count 2: {{pane.count2}}
  </div>
</div>

发布评论

评论列表(0)

  1. 暂无评论