Search code examples
javascriptangularjsangularjs-scope

Does an AngularJS watch fire upon object initialization


I'm currently working on an AngularJS app

I have an object which contains some boolean flags. I created a watch for one of such bool.

Does the watch fire upon object creation? Can the watch fire at random time even the boolean flag hasn't changed?


Solution

  • So we have (I'm working with Gianluca):

    scope.$watch("chartData.selectedIndicator", function() {
        if (chartData.selectedIndicator !== -1){
            highlightMessageIndicator(chartData.selectedIndicator);
        }
    }, true);
    

    ...despite not having updated chartData.selectedIndicator, this watch is still being hit and I am wondering if it is because within our chartData factory we are initialising selectedIndicator and this is why the watch is being hit?

    angular
        .module("app")
        .factory("chartData", [..., chartData]);
    
    function chartData(...) {
        var chartData = {
            selectedIndicator   : -1,
    

    I wonder if this would potentially be a case of just checking for newValue !== oldValue as suggested then?