Forms AngularJS无需绑定即可获取表单输入
我正在用AngularJS构建我的第一个应用程序,但我遇到了一个小问题 我得到了一个表,其中我呈现了users数组中的每个用户,如下所示:Forms AngularJS无需绑定即可获取表单输入,forms,data-binding,angularjs-scope,Forms,Data Binding,Angularjs Scope,我正在用AngularJS构建我的第一个应用程序,但我遇到了一个小问题 我得到了一个表,其中我呈现了users数组中的每个用户,如下所示: <table class="table table-hover"> <thead> <tr> <th>#</th> <th>Firstname</th>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Company</th>
<th>Active</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{[{ user.id }]}</td>
<td>{[{ user.firstname }]}</td>
<td>{[{ user.lastname }]}</td>
<td>{[{ user.email }]}</td>
<td>{[{ user.company }]}</td>
<td>Yes</td>
<td><a href="#modalUpdateUser" ng-click="getUser(user)" data-toggle="modal"><i class="icon-pencil"></i></a></td>
</tr>
</tbody>
</table>
在ModalBox中,所有输入字段都有ng model=“user.firstname”等。
因此,这当然会将ModalBox中的输入字段绑定到我的表中的用户,并在我在ModalBox中更改数据时立即更改表中的数据
但我想要的是编辑ModalBox中的数据,然后仅在按下ModalBox中的“Save”时更改表中的用户
所以我的问题是,我可以从我的表中的ng repeat中获取user对象,并将其交给我的$scope.user,该$scope.user绑定到我的ModalBox输入,而不将它们全部绑定在一起吗
提前感谢,
- 拉斯马斯·努森
解决方案解决方案是使用angular.Copy在不使用绑定引用的情况下传输对象。此处的工作示例:您可以创建一个
$scope.selectedUser
对象和一个$scope.selectedIndex
属性,该属性位于getUser()
函数中,并通过索引:
getUser(index){
$scope.selectedIndex = index;
$scope.selectedUser = $scope.users[index];
}
然后使用$scope.selectedUser
填充模式。用户单击“确定”后,可以使用索引替换数组中的用户
saveUser(){
$scope.users[$scope.selectedIndex] = $scope.selectedUser;
}
我不确定建议的解决方案@MaxWillmo是否有效,对象是通过引用复制的并将得到更新。。当它在弹出窗口中更改时 我认为您可能需要执行“angular.copy()”&复制所选用户,然后在编辑完成后替换数组中的用户对象 -巴斯卡拉
非常感谢,这本书正是我要找的。我在这里还找到了一个表单的工作示例:谢谢你的回答,尽管我已经尝试过了,但无论如何都会绑定对象引用。你可以通过复制你想要的属性来模拟selectedUser作为一个新对象,在作用域上创建一个新对象。然后,当你完成后,你可以把它们复制回来。
saveUser(){
$scope.users[$scope.selectedIndex] = $scope.selectedUser;
}