gpt4 book ai didi

javascript - Angularjs + 停止将数据更新到变量中

转载 作者:行者123 更新时间:2023-11-28 18:26:43 25 4
gpt4 key购买 nike

我正在使用 angularjs。我有一些不同类型的问题。

我有 HTTP 调用。 HTTP 请求后,响应将存储在两个不同的变量中。当我更改变量中的数据后,它也会自动更改为其他变量。

$http.get('get/list')
.success(function(data, status) {
$scope.test1 = data;
$scope.test2 = data;
})
.error(function(data) {

});

//示例 json

    {
"lists": [
{
"_id": "575e6d4bde006e3176bb9dc5",
"items": [
{
"name": "a"
}, {
"name": "b"
}
],
"name": "fridge",
"status": "done"
}
]
}

之后我会将 json 推送到 test1 变量中。

$scope.addRow = function(comment1) {
$scope.test1.lists.push({
'name' : 'c'
});

};

但是当我打印 $scope.test2 时,它也会自动添加新添加的项目。 (名称 = c)。

任何解决此问题的想法。我需要打印 test2 在 HTTP 请求中获取的内容。

最佳答案

发生这种情况是因为 $scope.test1$scope.test2 都引用了内存中的同一对象。使用 angular.copy 创建对象的深拷贝。因此,$scope.test1$scope.test2 将不再是彼此的别名

$http.get('get/list')
.success(function(data, status) {
$scope.test1 = angular.copy(data);
$scope.test2 = angular.copy(data);
})
.error(function(data) {

});

关于javascript - Angularjs + 停止将数据更新到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38977298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com