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

前端 未结 7 1754
执笔经年
执笔经年 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:51

    If you want to immidate an API-Rest-Call, use the returned promise in your Controller instead setting the scope inside the Rest-Call.

    $http.get('uri')
      .success(function(data) {
        $scope.items = data
    });
    

    Avoid using $apply(). From the Angular GitHub Repo:

    $scope.$apply() should occur as close to the async event binding as possible.

    Do NOT randomly sprinkle it throughout your code. If you are doing if (!$scope.$$phase) $scope.$apply() it's because you are not high enough in the call stack.

    To your question:

    • If you find yourself in a situation where you need $apply(), rethink your structure.
    • Just for safety reason: Never use $apply()

提交回复
热议问题