Javascript 为什么角度范围保持参考?
JSJavascript 为什么角度范围保持参考?,javascript,angularjs,scope,Javascript,Angularjs,Scope,JS angular.module('bindExample', []).controller('ExampleController', ['$scope', function($scope) { $scope.gridFields = { id: { width: 50 }, price: { width: 60 }, }; $scope.allData =
angular.module('bindExample', []).controller('ExampleController', ['$scope', function($scope) {
$scope.gridFields = {
id: {
width: 50
},
price: {
width: 60
},
};
$scope.allData = {
'one': {
id: '1234qwe',
price: 900
},
'two': {
id: 'asdadw',
price: 1700
},
'three': {
id: '342sdaw',
price: 1200
},
};
$scope.edit = function(row) {
console.log(row);
$scope.buffer = $scope.allData[row];
}
}]);
HTML
<div ng-app="bindExample">
<div ng-controller="ExampleController">
<table>
<tbody>
<tr ng-repeat="(row, data) in allData">
<td ng-repeat="(field, option) in gridFields" ng-bind="data[field]"></td>
<td><button ng-click="edit(row)">edit</button></td>
</tr>
</tbody>
</table>
<div>
<input type='text' ng-model="buffer.id"/>
</div>
<div>
<input type='text' ng-model="buffer.price"/>
</div>
</div>
</div>
编辑
单击编辑后,值从$scope.allData转到$scope.buffer变量,输入使用缓冲区作为模型,但当输入更改时,allData变量中的值也会更改,但我不希望这样,这就是为什么尝试将值传递给其他
此处举例说明的问题:
有什么想法吗?使用
首先,如果使用父级
对象
文本而不是数组(Angular并不保证它会按顺序遍历键),那么在ng repeat
中会得到意外的结果:
其次,发生这种情况的原因是Javascript将所有内容复制为引用,除非它是原语,所以在执行此操作时:
$scope.buffer = $scope.allData[row];
实际上,您只是将指向原始对象$scope.allData[row]
的指针存储在$scope.buffer
中
要做一个“深度复制”,你可以使用angular.copy,正如@Moncephassein bey在他的回答中所建议的那样 如果分配的数据是
函数
或对象
或数组
,Javascript将保留引用
它在许多方面为开发人员提供了巨大的好处。但是如果你想删除引用,你必须克隆它
使用角度
$scope.buffer = angular.copy($scope.allData[row]);
我接受@Moncephassein bey的回答,因为他是第一个提出解决方案的人,但我还是要感谢你的指导。我会记住的!
$scope.buffer = $scope.allData[row];
$scope.buffer = angular.copy($scope.allData[row]);