Area variable updated in angular, but the change does not affect the user

I have several angular variables set like this:

$scope.pane = []; $scope.pane.count = 0; $scope.pane.max = 5; 

Then I display the variables in HTML as follows:

 {{pane.count}} 

This works great and displays 0 as expected.

Now, if I update a variable at any time, this update will happen (I see using console.log), but the print version in HTML is not updated.

eg.

 setTimeout(function(){ $scope.pane.count = 1; },1000); 

I am using angular v1.3. What am I doing wrong?

+5
source share
2 answers

In order for angular to be aware of the changes, you must use the angular wrapper to time out.

Try the following:

 $timeout(function() { $scope.pane.count = 1; }, 1000); 

Typically, when you have a structure outside the angular world (like the jQuery plugin) that changes values, you need to call $ scope. $ apply () so that angular knows about them.

 $scope.$apply(); 
+15
source

setTimeout is outside the scope of angularjs, so you need to use $ scope. $ apply or $ timout, please see demo example below

 var app = angular.module('app', []); app.controller('homeCtrl', function($scope, $timeout) { $scope.pane = []; $scope.pane.count = 0; $scope.pane.count2 = 0; $scope.pane.max = 5; setTimeout(function() { $scope.$apply(function() { $scope.pane.count = 1; }) }, 1000); $timeout(function() { $scope.pane.count2 = 5; }, 2000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="homeCtrl"> <h3>setTimeout</h3> Count 1: {{pane.count}}<br/> <h3>$timeout</h3> Count 2: {{pane.count2}} </div> </div> 
+2
source

Source: https://habr.com/ru/post/1206634/


All Articles