问题
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