Search code examples
javascriptangularjswatchng-controller

$watch in angularJS is not working as expected


In my controller I want to be notified when a variable value is changed. My requirement is when value of a variable will change a function will be invoked. So I am using $watch. My code is as follow.

var Canvas = angular.module('canvas');

Canvas.controller("excelOperation",function($scope,Data,SharedData,$http){

    $scope.tbody=$scope.$parent.shared.previews;

     $scope.$watch('$parent.shared.previews',function(newVal,oldVal){
        console.log("WORKING");
     })

     setInterval(function(){
         console.log($scope.$parent.shared.previews);
     },1000)

    /**
     * Populate table function to populate excel table
     */
    $scope.populateTable=function()
    {

    }
})

angular.bootstrap(document.getElementById("page"), ['canvas']);

But issue is $watch is working only when I refresh my page. Though the setInterval is printing the changed value of the variable $watch is not being invoked.

N.B. $scope.$parent.shared.previews is an object

What am I doing wrong? And what I told to achieve, is this a good way to do?


Solution

  • You are watching a object's property change, deep watch is required. Second, to watch parent scope variable, maybe you'd better write like this $scope.$parent.$watch(...).

    var deepWatch = true;
    $scope.$watch('$parent.shared.previews', function(newVal, oldVal) {
        console.log("WORKING");
    }, deepWatch);