2014-03-31 33 views
0

我仍然與Angular一起弄溼了自己的腳,所以在閱讀我的問題時請牢記這一點。角度更新兩個不同的陣列,當只有一個應該更新

我有一系列動態生成的複選框可用於向其他用戶授予權限。每當更新複選框時,它會更新我在主控制器中設置的$ scope.permissions數組。該數組由AJAX請求填充,該請求在從下拉列表中選擇要管理的用戶時觸發。

我想通知用戶他們是否有未保存的更改,然後他們離開或更改他們想要管理的用戶。所以,我設置了一個第二陣列稱爲被設置爲相同的數據$ scopes.permission陣列originalPermissions,就像這樣:

$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通知你,只要權限數組更改,但無法確定它是否與最初設置時相同。

所以:爲什麼origPermissions會隨着範圍而更新?是否因爲我將每個數組設置爲相同的值,所以Angular認爲它基本上是一樣的東西?有沒有更好的方式來做到這一點,更符合「角度的方式」?

回答

1
 $scope.permissions = data; 
    $scope.origPermissions = data; 

數據「點」到相同的數組。

你可以用切片返回一個新的數組

 $scope.permissions = data.slice(); 
    $scope.origPermissions = data; 
+0

真棒。這使得它按照我的預期工作。我想知道這是否是一個「指針」問題,但我不知道這是JavaScript中的「事物」。你能告訴我:這是常見的JS行爲,還是Angular正在做的事情? – DocWatson

+0

這是因爲JavaScript,而不是角度。數組很像C中的指針集合。 – mpm