tidelipop
tidelipop

Reputation: 717

$watch is triggered directly after init, why?

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);
}

Upvotes: 31

Views: 12550

Answers (3)

David Vareka
David Vareka

Reputation: 262

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.

Upvotes: 2

SimonShyu
SimonShyu

Reputation: 95

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.

});

Upvotes: 0

Stewie
Stewie

Reputation: 60416

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

Upvotes: 49

Related Questions