Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $scope doesn't render after being updated

Tags:

angularjs

I have a controller that listens on $scope.$on, which will show a popup window when triggered. It works 100% of the time from a couple other controllers' $rootScope.$broadcast methods. But one of them won't work ever.

The controller gets the event, and sets the $scope variable needed, but the page doesn't update, even if I fire $scope.$eval(). Then, if I go to another route, the $scope will finally render, and the modal will pop up on top of that route. I can't tell if I've found a bug in angularjs, or I'm missing something fundamental.

like image 251
doubledriscoll Avatar asked Aug 20 '12 17:08

doubledriscoll


People also ask

What does $scope mean in AngularJS?

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).

Why $scope is used in AngularJS?

$scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive. It is available globally for all the controllers, i.e, the property assigned with “$rootscope” can be used anywhere.

What is the difference between $scope and this in AngularJS?

"How does this and $scope work in AngularJS controllers?" When the controller constructor function is called, this is the controller. When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on.

How do you access $scope in console?

scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .


2 Answers

You are probably changing the $scope outside of the angular $digest(). Try replacing code making changes with $scope.$apply(function(){ code making changes }). With this the dirty-check should run and update all.

like image 146
Renan Tomal Fernandes Avatar answered Sep 30 '22 01:09

Renan Tomal Fernandes


I would recommend using:

$scope.$evalAsync(function() { // scope changes here });

This way you won't run into problems like trying to call apply when there's a digest already in progress.

like image 41
emerino Avatar answered Sep 30 '22 00:09

emerino