Javascript 防止在初始化时触发$watchCollection
我有“Javascript 防止在初始化时触发$watchCollection,javascript,angularjs,Javascript,Angularjs,我有“$scope.posits”数组,我希望在每次更改时都保留该数组。因此,我在这个元素上放置了$scope.$watchCollection,以侦听更改并保存数据。问题是$watch在页面加载时被触发了3次(我的测试数组有3个条目)。 如何预防?我的代码怎么了 视图: 这最终将在$watch和第三个参数设置为true时起作用: $scope.$watch("postits", function (newValue, oldValue) { //this prevent $wa
$scope.posits
”数组,我希望在每次更改时都保留该数组。因此,我在这个元素上放置了$scope.$watchCollection
,以侦听更改并保存数据。问题是$watch在页面加载时被触发了3次(我的测试数组有3个条目)。
如何预防?我的代码怎么了
视图:
这最终将在$watch和第三个参数设置为true时起作用:
$scope.$watch("postits", function (newValue, oldValue) {
//this prevent $watch to be triggered on init
if(newValue === oldValue || oldValue === undefined ){
console.log("return") ;
return;
}
console.log("watch triggered") ;
console.log(oldValue);
console.log(newValue);
storage.save();
},true);
使用该解决方案,不需要使用任何标志
app.controller('postitController', function($scope, $http, $timeout) {
$scope.postitsLoaded = false;
var storage = {
endpoint: "localhost/backend/ws.php",
get: function() {
$http({
method: 'GET',
url: this.endpoint
}).then(function successCallback(response) {
$scope.postits = response.data;
$scope.postitsLoaded = true;
console.log("init done") ;
}, function errorCallback(response) {
console.log(response);
});
},
save: function () {
$http({
method: 'POST',
url: this.endpoint,
data: "postits="+ angular.toJson($scope.postits),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
alert("error");
});
}
}
$scope.$watchCollection("postits", function (newValue, oldValue) {
if(newValue === oldValue || !$scope.postitsLoaded){
console.log("return") ;
return;
}
console.log("watch triggered") ;
storage.save();
});
$scope.addPostit = function() {
$scope.postits.push({id:100,content:"foobar"});
storage.save();
};
$scope.removePostit = function(postit) {
$scope.postits.splice($scope.postits.indexOf(postit), 1) ;
storage.save();
};
storage.get();
});
$scope.$watch("postits", function (newValue, oldValue) {
//this prevent $watch to be triggered on init
if(newValue === oldValue || oldValue === undefined ){
console.log("return") ;
return;
}
console.log("watch triggered") ;
console.log(oldValue);
console.log(newValue);
storage.save();
},true);