32

Why does $watch trigger directly after page load and how can I prevent this?

http://jsfiddle.net/dcSRu/2/

function MyCtrl($scope) {
    // Init scope vars
    $scope.data_copy = {};

    // If data_copy changes...
    $scope.$watch("data_copy", function(newValue, oldValue) {

        alert("$watch triggered!");

    }, true);
}
Uli Köhler
  • 12,474
  • 14
  • 64
  • 110
tidelipop
  • 727
  • 2
  • 7
  • 10
  • This is also the case if you had a controller or directive which was initiated some time after page load. – Andrew Aug 27 '14 at 06:48

3 Answers3

50

On first run both values (newValue and oldValue) are equal, so you may easily escape it by checking for equality:

$scope.$watch("data_copy", function(newValue, oldValue) {
  if(newValue === oldValue){
    return;
  }
  alert("$watch triggered!");
});

PLUNKER

Stewie
  • 60,140
  • 20
  • 145
  • 113
2

Wrap $watch function into angular ready function.

angular.element(document).ready(function() 
{ 
  $scope.$watch("data_copy", function(newValue, oldValue) {
    alert("$watch triggered!");
  }, true);
})

When angular loads page. It changes values and $watch is triggered.

David Vareka
  • 216
  • 2
  • 6
0

There already have a very nice discussion in here:

How do I ignore the initial load when watching model changes in AngularJS?

$scope.$watch('fieldcontainer', function (new_fieldcontainer, old_fieldcontainer) {

if (typeof old_fieldcontainer === 'undefined') return;

// Other code for handling changed object here.

});

Community
  • 1
  • 1
SimonShyu
  • 95
  • 8