对象还在

时间:2013-08-08 16:54:03

标签: angularjs angularjs-scope angular-ui

我正在使用Angular来显示用户表。我创建了一个表单来添加和编辑用户。单击用户行时,我将该特定用户传递给控制器​​中的函数:

$scope.editUser = function (selectedUser) {
    $scope.userToAdd = selectedUser;
};

在上面的函数中,我创建了一个新对象$ scope.userToAdd。问题是,一旦selectedUser被传递到$ scope.userToAdd,在绑定到userToAdd的表单中发生的更改将反映在selectedUser中。这会给我带来麻烦,因为当有人更改某个值然后点击取消时;现在,更改将反映在用户表中。这种情况的角度最佳实践是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用angular.copy复制正在编辑的用户。然后,当他们单击“保存”时,您将用户复制回来:

$scope.editUser = function (selectedUser) {
    // Note: you might want to save the user's index or something so you can
    // know where to return the user, like this:
    $scope.userToAdd = angular.copy(selectedUser);
};

如果要在循环中渲染用户,可以执行以下操作:

<li ng-repeat="user in users">
    ...
    <button ngclick="editUser(user, $index);">Edit</button>
</li>

JavaScript的:

$scope.editUser = function(selectedUser, index) {
    // Note: you might want to save the user's index or something so you can
    // know where to return the user, like this:
    $scope.userToAdd = angular.copy(selectedUser);
    $scope.userToAddIndex = index;
};

$scope.saveUser = function() {
    // You may want to user angular.copy() here again, to prevent accidental
    // modification of the user.
    $scope.users[$scope.userToAddIndex] = $scope.userToAdd;
};