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); }
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With