Durga
Durga

Reputation: 15604

watch an object in controller 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

Upvotes: 5

Views: 211

Answers (2)

Veera Bhadra
Veera Bhadra

Reputation: 200

We can use watchgroup for this

$scope.$watchGroup(['form.name', 'form.age'], function(newValues, oldValues, scope) {
//...
});

Upvotes: 1

aorfevre
aorfevre

Reputation: 5064

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:

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/

Upvotes: 2

Related Questions