How can I tell AngularJS to “refresh”

前端 未结 3 792
滥情空心
滥情空心 2020-11-28 20:58

I have a click event that happens outside the scope of my custom directive, so instead of using the \"ng-click\" attribute, I am using a jQuery.click() listener and calling

相关标签:
3条回答
  • 2020-11-28 21:13

    The solution was to call...

    $scope.$apply();
    

    ...in my jQuery event callback.

    0 讨论(0)
  • 2020-11-28 21:30

    Why $apply should be called?

    TL;DR: $apply should be called whenever you want to apply changes made outside of Angular world.


    Just to update @Dustin's answer, here is an explanation of what $apply exactly does and why it works.

    $apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

    Angular allows any value to be used as a binding target. Then at the end of any JavaScript code turn, it checks to see if the value has changed. That step that checks to see if any binding values have changed actually has a method, $scope.$digest()1. We almost never call it directly, as we use $scope.$apply() instead (which will call $scope.$digest).

    Angular only monitors variables used in expressions and anything inside of a $watch living inside the scope. So if you are changing the model outside of the Angular context, you will need to call $scope.$apply() for those changes to be propagated, otherwise Angular will not know that they have been changed thus the binding will not be updated2.

    0 讨论(0)
  • 2020-11-28 21:39

    Use

    $route.reload();
    

    remember to inject $route to your controller.

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