当只应该更新一个数组时,角度更新两个不同的数组

Angular updating two different arrays when only one should be updated

本文关键字:数组 更新 两个 一个      更新时间:2023-09-26

我仍然在用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;