17

I have the following action

ng-click in my view -> which inturn calls a jQuery ajax function that displays jQuery Qtip -> In the Qtip popup I have an ng-click on an element -> which performs a $http post and has some callbacks to update $scope values.

So all these things are happening properly. But the updates are not getting reflected in the view as per the changes made in the callback in the final stage.

I have a function for "ng-mousemove" in my view. So whenever I move my mouse, the updates in the view are getting reflected.

What am I doing wrong here? Is the because of transitioning between angular and non-angular? Can anyone help me how to solve this?

2 Answers 2

36

As the docs explains:

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

So if you have a jQuery code like

$('#myDiv').on('click', function() {
  // do stuff
  $scope.$apply();
});
Sign up to request clarification or add additional context in comments.

3 Comments

In my code, I have only ng-click that calls the angular function. I do jQuery.qtip() inside that angular function. That jQuery.qtip also does a jQuery post internally to get the content of Qtip. But the digest is already running when I try to do apply after the qtip() function is being called. What is the right place for $apply? Shouldn't that be called after the qtip is rendered?
An Angular nerd told me to use if(!$scope.$$phase) $scope.$apply();
In addition, the safest way to call $scope.$apply is : if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') { $scope.$apply(); }
4

You have to tell angular Js something has changed with $scope.$apply().

Here is a nice blog on why: http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.