I have some code that is not behaving as expected... I have an event listener within a AngularJS controller like this:
$scope.$on("newClipSelected", function(e) { $scope.$apply(function() { $scope.isReady = true; }); });
The controller's markup has a ng-show='isReady'. When this event handler runs, the ng-show region shows as expected. However, this event handler does not work:
$scope.$on("newClipSelected", function(e) { $scope.isReady = true; });
With this event handler, if I use the debugger to expect the AngularJS scope I do see that $scope.isReady=true, however the ng-show element is not showing.
Its my understanding that $scope.$on will in fact call $watch/$apply as appropriate. So why am I needing to call $apply in this case?
The event is being triggered by a call to $rootScope.$broadcast() within a non-angularJS asynchronous completion event.
Scopes provide APIs ($apply) to propagate any model changes through the system into the view from outside of the "AngularJS realm" (controllers, services, AngularJS event handlers). Scopes can be nested to limit access to the properties of application components while providing access to shared model properties.
The $scope. $apply() function takes a function as parameter which is executed, and after that $scope. $digest() is called internally. That makes it easier for you to make sure that all watches are checked, and thus all data bindings refreshed.
In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever $apply() is called to update the data bindings.
There are two types of scopes in Angular JS. How to use the Scope? When we make a controller in AngularJS, we will pass the $scope object as an argument. In AngularJS, it creates and injects a different $scope object into each controller in an application.
No, angular doesn't fire $apply
on the events so if $broadcast
is called outside angular's context, you are going to need to $apply
by hand.
Check the source here
$on
and $broadcast
doesn't call $apply
for you, you need to call it yourself. I'm not sure why that is, but my guess is that it's because a digest is a bit expensive, and it would be a cost to run a digest cycle for every event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With