在 Angularjs 中更新模型 [英] Updating Model in Angularjs

查看:25
本文介绍了在 Angularjs 中更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 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);
    });

推荐答案

使用 angular.copy() 制作一个副本,这样您就不会每次都将同一对象的引用推送到数组中.

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

这篇关于在 Angularjs 中更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆