Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

angularjs - Infinite loop with Angular expression binding

I have an angular application that displays the value returned by a controller method through a simple expression binding:

<div>{{getValue()}}</div>

If the method in question just returns a value, the method is called twice, and that is strange enough:

$scope.getValue = function(){
  return 'some value';
}

But if the method does some asynchronous work such as getting a file from the server, the code goes into an infinite loop:

$scope.getValueAsync = function(){
  $http.get('myfile.html')
    .success(function (data, status, headers, config) {
      return 'some async value';
    });

  return 'file not found'; // same value returned every time but $digest cycle still loops
}

I'm new to Angular so have probably missed something basic here, but can someone please explain what is going on?

Plunker

Here's a plunker to play with http://plnkr.co/7BriYDbdVJvIoIigQcTU

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even though your async function returns the same exact string every time, the $digest cycle is fired in loops because your function also makes an ajax call with $http service.

$http service triggers $rootScope.$apply() when requests are completed and since $apply triggers a $digest cycle it makes your view expression to be re-evaluated, which in return causes your async function to be called again, and so on...

app.controller('MainCtrl', function($scope, $http) {

  $scope.getValue = function(){
    return 'some value';
  }

  $scope.getValueAsync = function(){
    $http.get('myfile.html')
      .success(function (data, status, headers, config) {
        return 'some async value';
      });

    return 'file not found';
  }
});
<div>{{getValueAsync()}}</div>

Moral of the story: If you use functions in expressions, make sure your functions don't affect something outside of them that would trigger a $digest loop, and make sure your functions always return the same output given the same input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...