Reputation: 175
var app = angular.module('app', []);
app.controller('TheCtrl', ['$scope', function (scope) {
scope.user = {
name: "木士羽",
email: '[email protected]',
};
scope.$watch('user.name', function () {
console.log('change');
});
}]);
angular.bootstrap(document.documentElement, ['app']);
when page is loaded, 'change' is printed in console.
$watch
is triggered when init. How to avoid it?
Upvotes: 2
Views: 846
Reputation: 77914
what about this approach:
1st time oldValue
will be equal to newValue
, so avoid this by if
validation.
$scope.$watch(
function() {
return $scope.user.name;
},
function(newValue, oldValue) {
if (oldValue !== newValue) {
// .....
}
});
Demo Fiddle
BTW, its a good practice to write if (oldValue !== newValue){ /* ...*/}
in watchers to avoid additional code execution under watch
Upvotes: 4
Reputation: 874
For the first time you can initialize a flag to true and once the watch is triggered it can be set to false. So that watch does not get triggered. var firstTime = true and then when the first $watch fires, do
$scope.$watch('testValue', function() {
if (firstTime) {
$timeout(function() { firstTime = false; });
} else {
//perform operation.
}
Second method which is recommended by the angular doc The first time watch listener is called, the old value and the new value are identical. so check for not equal condition as given below
$scope.$watch('testValue', function(newValue, oldValue) {
if (newValue !== oldValue) {
// perform your operation
}
});
Upvotes: 0
Reputation: 6342
As per the docs you should be checking whether the new value and old value differ e.g.
$scope.$watch('user.name', function(newVal, oldVal) {
if (newVal !== oldVal) {
// Do something with newVal
}
});
Upvotes: 0
Reputation: 1826
scope.$watch('user.name', function (val) {
if (val !== undefined) {
console.log('change');
}
});
Upvotes: -1