Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS- why am I needing $scope.$apply within $scope.$on?

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.

like image 993
Frank Schwieterman Avatar asked Mar 14 '14 19:03

Frank Schwieterman


People also ask

What is the use of scope apply in AngularJS?

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.

Why we use scope apply ()?

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.

When to use $apply in AngularJS?

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.

What is the number of scopes allowed in an AngularJS application?

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.


2 Answers

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

like image 140
Jesus Rodriguez Avatar answered Sep 16 '22 16:09

Jesus Rodriguez


$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.

like image 21
Anders Ekdahl Avatar answered Sep 19 '22 16:09

Anders Ekdahl