When is it safe to use $scope.$apply()?

前端 未结 7 1762
执笔经年
执笔经年 2020-12-09 17:47

I guess the title is pretty much clear what I am asking. I have created this fiddle : http://jsfiddle.net/Sourabh_/HB7LU/13142/

In the fiddle I have tried to replica

7条回答
  •  死守一世寂寞
    2020-12-09 18:43

    Edit It was not clear the OP was trying to mock a backend call. Even so, using the $timeout service is a great way to avoid the need of calling $scope.$apply manually and is a more generally applicable solution than using a Promise (in cases where you're i.e. not calling $http it doesn't always make sense to force your changes into the next cycle by wrapping them with a Promise).


    Update your code to use the $timeout service and it should work without having to call $apply.

    $timeout is a wrapper around the native setTimeout with an important difference: $timeout will delay the execution at least until the next $digest cycle runs.

    So passing in no delay will still delay the execution up until the next cycle. Passing in 2000 will delay the execution up to the next cycle after 2000ms.

    Hence, this is an easy trick to make sure your changes are picked up by Angular without ever having to call $apply manually (which is considered unsafe in any case)

    function MyCtrl($scope, $timeout) {
      $scope.items = [{name : "abc"},{name : "xyz"},{name : "cde"}];
    
      $scope.change = function(){
        test(function(testItem){
          $scope.items = testItem;
          //$scope.$apply();
        })
      }
      function test(callback){
        var testItem = [
                        {name : "mno"},
                        {name : "pqr"},
                        {name :   "ste"}
                       ];
        $timeout(function(){callback(testItem)},2000);
      }
    }
    

提交回复
热议问题