2017-02-20 174 views
1

我有「$scope.postits」數組,我想在每次更改時都保留這個數組。因此,我在此元素上放置$scope.$watchCollection以偵聽更改並保存數據。問題是$ watch在頁面加載時被觸發3次(我的測試數組有3個條目)。 如何防止?我的代碼有什麼問題?

觀點:

<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 cool and have a beer there's no postit here !</div> 
    </div> 
</div> 

JS控制器:

$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(); 
}); 

回答

1

這是最後用$手錶,第三個參數設置爲true工作不需要使用任何標誌。