我还在和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()存在于angular中,但据我所知,每当权限数组发生变化时,watchCollection会通知你,但是无法判断它是否与最初设置时相同。< / p>
那么:为什么origPermissions会随着范围一起更新?是因为我将每个数组设置为相同的值,所以Angular假设它基本上是相同的东西?是否有更好的方法来实现这一点,更符合“Angular方式”?
答案 0 :(得分:1)
$scope.permissions = data;
$scope.origPermissions = data;
数据“指向”同一个数组。
您可以使用slice返回新数组
$scope.permissions = data.slice();
$scope.origPermissions = data;