Avoiding timeouts in Angular applications

后端 未结 2 950
长情又很酷
长情又很酷 2021-01-23 07:22

I have a problem that I was able to solve, using a timeout. This feels like a very bad practice that could lead to an unmaintainable mess, and I am looking for a better way to s

相关标签:
2条回答
  • 2021-01-23 07:53

    scope.$apply() may help :

     $scope.fillAndSend = function() {
        $scope.model = 'fail';
        $scope.$apply();
        $scope.send();
        /* using a timeout works
        $timeout(function(){
            $scope.send();    
        },0);
        */
    }
    
    0 讨论(0)
  • 2021-01-23 08:07

    I believe this is because the angular $digest cycle is happening just once here. Using the $timeout, forces the second part of what you do into a second digest cycle, which is why it works with the $timeout. You can't just call $scope.$apply() because you are already in a digest cycle. In this case, using the timeout is the correct thing to do because you need angular to realize the model changed, and THEN call the send function.

    The other option is to set a flag in the controller that send is needing to be called since you are changing the model. And then in your directive where you watch the model you could check to see if you need to call send

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