問題是這樣的:
$scope.model1 = [1,2,3,4,5,6,7];
$scope.model2 = $scope.model1;
$scope.model2.splice(2, 1);
<pre>{{model1}}</pre>
<pre>{{model2}}</pre>
返回:
[1,2,4,5,6,7]
[1,2,4,5,6,7]
極品:
[1,2,3,4,5,6,7]
[1,2,4,5,6,7]
請幫助。如果有人解釋爲什麼會發生這種情況,那將會很好嗎?
UPD: 解決方案:到處使用angular.copy($scope.val)
我的代碼是壞:
$scope.$watch('checkedImages', function (newVal) {
if (newVal !== undefined && newVal[0] !== undefined) {
if ($scope.model.curSupplier === undefined) {
$scope.model.curSupplier = newVal[0].supplier_id;
$scope.model.curCheckedImages = newVal;
}
$scope.supplier = newVal[0].supplier_id;
}
});
VS
$scope.$watch('checkedImages', function (newVal) {
if (newVal !== undefined && newVal[0] !== undefined) {
if ($scope.model.curSupplier === undefined) {
$scope.model.curSupplier = angular.copy(newVal[0].supplier_id);
$scope.model.curCheckedImages = angular.copy(newVal);
}
$scope.supplier = angular.copy(newVal[0].supplier_id);
}
});
隨處使用'angular.copy'不是一個好主意。有時,當你改變指令中的某個值時(例如,如果你在'ng-model'中使用屬性),你確實希望修改原始對象。 –