【发布时间】:2016-03-02 01:58:37
【问题描述】:
我通过使用 Promises 下载 JSON 数据并将其存储在变量中来开始我的 Angular 控制器:
app.controller('mainController', ['$scope', '$http', '$q', function($scope, $http, $q) {
var req1 = $http({method: 'GET', url: 'link to JSON 1', cache: 'true'});
var req2 = $http({method: 'GET', url: 'link to JSON 2', cache: 'true'});
$q.all([req1, req2]).then(function(response){
var res1 = response[0].data;
var res2 = response[1].data;
$scope.data1 = res1; // JSON which I will manipulate
$scope.data1Ref = res1; // JSON for reference which I won't manipulate
$scope.data2 = res2;
$scope.data2Ref = res2;
init(); // do the stuff with the data
});
}]);
然而,在init() 完成后,如果我检查$scope.data1 和$scope.data1Ref 它们都已被修改,那就是它们被绑定在一起了。
为什么会发生这种情况?如何确保保留原始下载 JSON 的存储版本以供参考?
【问题讨论】:
-
这是因为 $scope.data1 和 $scope.data1Ref 引用了 res1 所以对 res1 的任何更改都会反映在这两个中。您需要在分配 res1 之前对其进行复制。
标签: javascript angularjs angularjs-scope angularjs-bindings