当只应该更新一个数组时,角度更新两个不同的数组
Angular updating two different arrays when only one should be updated
我仍然在用Angular弄湿我的脚,所以当你读到我的问题时,请记住这一点。
我有一系列动态生成的复选框,可用于向其他用户授予权限。每当更新复选框时,它都会更新我在主控制器中设置的 $scope.permissions 数组。该数组由 AJAX 请求填充,当从下拉列表中选择要管理的用户时,将触发该请求。
我想在用户离开或更改要管理的用户之前通知用户是否有未保存的更改。因此,我设置了一个名为 originalPermissions 的第二个数组,该数组设置为与 $scopes.permission 数组相同的数据,如下所示:
$http.post(ajaxurl, user_data)
.success(function(data) {
// Get the permissions model from the server and store to the $scope
console.log('Setting');
$scope.permissions = data;
$scope.origPermissions = data;
...}
然后,每个复选框都有一个ng-click="updatePermission(data.path)"
函数调用。它喜欢这样:
$scope.updatePermission = function (path) {
//get the position of the target path in the array
var position = $scope.permissions.indexOf(path);
//if it doesn't exist, its position will be -1
if(position == -1){
// Push the path into the Array if it doesn't exist
$scope.permissions.push(path);
} else {
// Remove the permission from the array if it was already there
$scope.permissions.splice(position, 1);
}
console.log('Perms: '+$scope.permissions);
console.log('OldPerms: '+$scope.origPermissions);
}
即使我只在$scope.permissions
数组上执行推送,$scope.origPermissions
数组也在更新(console.logs 输出相同的东西)。这是不可取的,因为我想看看权限中的新内容是否与我们在 origPermissions 中的内容不同;如果是这样,我想触发一个确认框,上面写着"您有未保存的更改..."等。
也就是说,我知道watchCollection()以角度存在,但据我所知,watchCollection会在权限数组更改时通知您,但是无法判断它是否与最初设置时相同。
那么:为什么原始权限会随着范围一起更新?是因为我将每个数组设置为相同的值,所以 Angular 假设它本质上是相同的吗?有没有更好的方法来做到这一点,更符合"角度方式"?
$scope.permissions = data;
$scope.origPermissions = data;
数据"指向"同一数组。
您可以使用切片返回新数组
$scope.permissions = data.slice();
$scope.origPermissions = data;
相关文章:
- 如何通过数组更新角度子范围
- 如何创建独立于数组更新的组件列表
- 使用数组更新完整日历
- 数组更新后的敲除绑定
- c3js - 使用 chart.load() 使用颜色数组更新图表颜色
- 猫鼬位置数组更新
- 如何使用新数组更新 dom-repeat 列表
- .click在Javascript中没有任何效果 - 应该基于数组更新两个元素
- Angular2 从后端服务中的数组更新视图
- 推送前的数组更新 - javascript
- 使用 ajax 使用 jquery 数组更新 mysql 数据库
- Javascript二维字符串数组更新值
- 如何将数组更新到firebase
- Meteor AutoForm:如何用子文档数组更新模式值
- 为什么当数组更新时,引用数组元素的n't是我的对象
- 从类型化数组更新svg路径
- 聚合物dom-repeat如何通知数组更新
- 什么时候改变子数组更新子数组vs.创建一个新的子数组?[JavaScript]
- 当Javascript中的数组更新时,如何使用PHP更新和插入数据库
- 使用修改后的数组更新对象属性值