Infinite loop with Angular expression binding

后端 未结 2 989
傲寒
傲寒 2020-11-30 11:43

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



        
相关标签:
2条回答
  • 2020-11-30 12:06

    I met the same problem as you, to fix the problem we can cache the results of the function. For this purpose I prefer to use Lo-Dash’s memoize function. I create a demo to show you how i managed to fix this problem.The following link contains the demo:http://plnkr.co/edit/KBmk4J2ZCt0SsmZlnKZi?p=preview

    0 讨论(0)
  • 2020-11-30 12:10

    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.

    0 讨论(0)
提交回复
热议问题