AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

前端 未结 28 2695
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:31

I\'m finding that I need to update my page to my scope manually more and more since building an application in angular.

The only way I know of to do this is to call

28条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:21

    I would advise you to use a custom event rather than triggering a digest cycle.

    I've come to find that broadcasting custom events and registering listeners for this events is a good solution for triggering an action you wish to occur whether or not you are in a digest cycle.

    By creating a custom event you are also being more efficient with your code because you are only triggering listeners subscribed to said event and NOT triggering all watches bound to the scope as you would if you invoked scope.$apply.

    $scope.$on('customEventName', function (optionalCustomEventArguments) {
       //TODO: Respond to event
    });
    
    
    $scope.$broadcast('customEventName', optionalCustomEventArguments);
    

提交回复
热议问题