I am using an angular module then sends messages and I am trying to set a variable to true or false but I notice that they do not get updated in the UI unless I wrap them inside a $apply. Is this the best way of doing this?
This is my working code, remove the $apply and although the variable is updated - the view never updates.
$scope.$on('duScrollspy:becameActive', ($event, $element, $target) => {
$scope.$apply(() => {
this.ready = true;
});
});
Anyone any ideas on the best way to fix this? Calling $apply seems like a code smell, I know listening for events on the scope isn't considered good practice but this is a third party Angular module.
Modifying the scope inside an event requires a call to $apply().
(this
is bound to the scope btw)
There's no way around it. (if you need the view updated.)
$apply
is actually called automatically in many places like $http promise resolve code (https://github.com/angular/angular.js/blob/master/src/ng/http.js line 1331-1351) but it's not called on events.
Note, line numbers may change. Search for function done()
So this is not code smell, this is standard.