角度通过引用更新范围对象 - 问题

时间:2015-04-20 23:21:19

标签: javascript angularjs

我在更新对象引用时遇到问题: 我有几个功能可以帮助我编辑用户:

function enableEditUser(user) {
            $scope.originalUser = user;
            $scope.editUser = angular.copy(user);
        }

function SaveUserEdits(form) {
            if (form.$valid) {
                $scope.originalUser = angular.copy($scope.editUser);
            }
        }

一切都按照我的预期运作。我从用户"中的ng-repeat ="用户内部调用enableEditUser(user)并且用户被传入。当我调用SaveUserEdits时,原始用户对象确实得到了更新。

我期望,因为$scope.originalUser = user;,当我更新$ scope.originalUser时,用户中的用户也会被更新(因为我认为它们都是对同一对象的引用)。但是,(使用ng-inspect)我看到,当$ scope.originalUser更新时,用户不会更新。

提前致谢

1 个答案:

答案 0 :(得分:4)

您需要更改

// In this case you have lost reference to user object
$scope.originalUser = angular.copy($scope.editUser);

为:

angular.extend($scope.originalUser, $scope.editUser)

解释angular.copy:

var user = {name: 'John', age: 30},
        editUser, originalUser;
originalUser = user;
console.log(originalUser); // => {name: 'John', age: 30}
user === originalUser; // => true
editUser = angular.copy(user);
console.log(editUser); // => {name: 'John', age: 30}
user === editUser; => false
angular.extend(originalUser, editUser);
originalUser === user; // => true;
editUser === angular.copy(editUser); // => false
originalUser = angular.copy(editUser); // you have overwritten the reference to user with reference to new object angular.copy(editUser). Hence you have lost you reference to user.
originalUser === user; // => false;

angular.copy和angular.extend的最简单版本:

function copy(src) {
   var newObject = {};
   Object.keys(src).forEach(function(key) {
       newObject[key] = src[key];
   })
   return newObject;
}

function extend(dst, src) {
   Object.keys(src).forEach(function(key) {
       dst[key] = src[key];
   })
   return dst;
}

// do not use this functions only for explaining