I have an array called "$scope.postits" that I want to persist every time it changes. To achieve this, I added a $scope.$watchCollection on this element to monitor changes and save the data. The issue is that the $watch function gets triggered 3 times when the page loads (due to my test array having 3 entries). How can I prevent this? What could be wrong with my code?
View:
<div ng-controller="postitController as postit" class="container animate-bottom">
<h2>Post-it !</h2>
<div class="btn-container">
<button ng-click="addPostit()" id="add-new-note" class="btn btn-primary">Add postit</button>
</div>
<div class="post-it-container">
<div ng-repeat="postit in postits" class="postit">
<a ng-click="removePostit(postit)" class="delete-postit glyphicon glyphicon-remove"></a>
<textarea ng-model="postit.content" ></textarea>
</div>
<div ng-if="postits.length==0" class="no-postit well lead">Keep calm and enjoy a beer! There are no post-its here.</div>
</div>
</div>
JS Controller :
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("initialization 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("returning") ;
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();
});