Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

watch an object in controller Angularjs

Tags:

angularjs

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.form = {
        name: 'my name',
        age: '25'
    }

    $scope.$watch('form', function(newVal, oldVal){
        console.log(newVal);
    },true);
    
    $scope.foo= function(){
    $scope.form.name = 'abc';
    $scope.form.age = $scope.form.age++;
    }
    $scope.foo();
    
    $scope.bar= function(){
    $scope.form.name = 'xyz';
    $scope.form.age = $scope.form.age++;
    }
    $scope.bar();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">{{form}}<br>
<label>Name:</label> <input type="text" ng-model="form.name"/><br>
        <label>Age:</label> <input type="text" ng-model="form.age"/>  </div>

In controller I changed 'form' object property four time,But $watch not firing. From UI(input) if I change it works

like image 999
Durga Avatar asked Oct 17 '22 11:10

Durga


1 Answers

Your case is that I assume that the angular Digest cycle did not had time to pass during all your rapid updates.

Here is some references to understand more the digest cycle of Angular 1.X:

  • https://www.thinkful.com/projects/understanding-the-digest-cycle-528/ https://www.ng-book.com/p/The-Digest-Loop-and-apply/

The prevent that kind of behaviour; your can force the digest to pass using $timeout ( that has a $apply) dependency : https://docs.angularjs.org/api/ng/service/$timeout

Example:

$timeout(function(){
    $scope.form.name = name;
    $scope.form.age = $scope.form.age++;
})

I have created a jsfiddle to illustrade your case :

http://jsfiddle.net/IgorMinar/ADukg/

like image 107
aorfevre Avatar answered Oct 21 '22 04:10

aorfevre