Updating Model in Angularjs

白昼怎懂夜的黑 提交于 2019-12-12 05:28:21

问题


Here is the plnkr : http://plnkr.co/edit/s9MwSbiZkbwBcPlHWMAq?p=preview

If I add information twice, latest data are the same, how can I prevent model from updating?

 $scope.personList = [];
  $scope.newPerson = {};
  $scope.columns = [{ field: 'Name' }, { field: 'Country' }];
  $scope.gridOptions = {
    enableSorting: true,
    columnDefs: $scope.columns,
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
    }
  };

  $scope.addPerson = function(){

  $scope.personList.push($scope.newPerson);

}

  $http.get('file.json')
    .success(function(data) {
      $scope.personList = data.records; 
      $scope.gridOptions.data = data.records;
      console.log($scope.gridOptions.data);
    });

回答1:


Make a copy using angular.copy() so you aren't pushing reference to the same object into the array each time.

$scope.addPerson = function(){
  var newPerson= angular.copy($scope.newPerson);
  $scope.newPerson ={}; // reset to clear view
  $scope.personList.push(newPerson);    
}



回答2:


What you need to do is, you need to check the index of the item in the list before pushing into it. If the index > -1 then push.

$scope.addPerson = function(){

  if($scope.personList.indexOf($scope.newPerson > -1){
    $scope.personList.push($scope.newPerson);
  }
}



回答3:


Here is a plunker with the solution:

You should add this function :

$scope.containsObject= function(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
    if (list[i] === obj) {
        return true;
    }
}

return false;

}

which will be called inside

  $scope.addPerson = function(){

if (!$scope.containsObject($scope.newPerson, $scope.personList)) {

  $scope.personList.push($scope.newPerson);
 $scope.newPerson.Name = '';
 }
}



回答4:


I guess this is what you are trying to do.

Updated Plnkr

Change in JS

$scope.addPerson = function(){

    $scope.personList.push(angular.copy($scope.newPerson)); //optional to use angular.copy()
    $scope.newPerson={}; //reset the object rather than one field
  }


来源:https://stackoverflow.com/questions/30212088/updating-model-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!