这是plnkr:http://plnkr.co/edit/s9MwSbiZkbwBcPlHWMAq?p=preview
如果我添加两次信息,最新数据是相同的,我该如何防止模型更新?
$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);
});
答案 0 :(得分:1)
使用angular.copy()
制作副本,这样您每次都不会将对同一个对象的引用推送到数组中。
$scope.addPerson = function(){
var newPerson= angular.copy($scope.newPerson);
$scope.newPerson ={}; // reset to clear view
$scope.personList.push(newPerson);
}
答案 1 :(得分:1)
我想这就是你要做的事。
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
}
答案 2 :(得分:1)
您需要做的是,在推入之前需要检查列表中项目的索引。如果指数> -1然后按。
$scope.addPerson = function(){
if($scope.personList.indexOf($scope.newPerson > -1){
$scope.personList.push($scope.newPerson);
}
}
答案 3 :(得分:1)
以下是solution:
的掠夺者你应该添加这个功能:
$scope.containsObject= function(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
将在
中调用 $scope.addPerson = function(){
if (!$scope.containsObject($scope.newPerson, $scope.personList)) {
$scope.personList.push($scope.newPerson);
$scope.newPerson.Name = '';
}
}