Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch is triggered directly after init, why?

Tags:

angularjs

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); } 
like image 864
tidelipop Avatar asked Apr 08 '13 08:04

tidelipop


2 Answers

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

like image 64
Stewie Avatar answered Oct 05 '22 19:10

Stewie


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.

like image 22
David Vareka Avatar answered Oct 05 '22 18:10

David Vareka