Reputation: 717
Why does $watch trigger directly after page load and how can I prevent this?
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
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
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