Javascript AngularJS视图没有';将$http响应分配给$scope时,不会更新
对于许多值,我有一个Javascript AngularJS视图没有';将$http响应分配给$scope时,不会更新,javascript,angularjs,angularjs-scope,angularjs-ng-repeat,angular-http,Javascript,Angularjs,Angularjs Scope,Angularjs Ng Repeat,Angular Http,对于许多值,我有一个ng repeat循环。循环时,我从另一个值数组中获取一个变量,并使用该变量: <div ng-repeat="i in [1,2,3]"> <div ng-init="obj = getObject(i)"> <pre>{{ obj }} </pre> </div> </div> {{obj}} 我现在的目标是更改该变量的属性,并执行包含更新变量的POST请求。然后
ng repeat
循环。循环时,我从另一个值数组中获取一个变量,并使用该变量:
<div ng-repeat="i in [1,2,3]">
<div ng-init="obj = getObject(i)">
<pre>{{ obj }} </pre>
</div>
</div>
{{obj}}
我现在的目标是更改该变量的属性,并执行包含更新变量的POST请求。然后,来自服务器的响应包含所有值,为了更新视图,我将这些值绑定到$scope
<div ng-repeat="i in [1,2,3]">
<div>
<pre>{{ getObject(i) }} </pre>
</div>
</div>
,它只模拟HTTP请求。然而,我发现,即使在我对REST后端运行此代码时,第一次一切正常,但之后每次都没有任何变化。我对您的小提琴进行了更改
$scope.changeType = function(ids, type) {
angular.forEach($scope.objects, function(o) {
if (ids.indexOf(o.id) > -1) {
o.type = type;
var response = (type === 2) ? allTwo : allThree
$scope.objects = angular.copy(response);
}
});
};
更新的fiddle的链接是我认为问题是因为您使用的是ng init
,这可能会设置一个不变的值,因为您正在调用函数。一旦您将{{obj}}
更改为{{getObject(i)}}
,它就会工作。唯一的问题是,您的变量也在脚本中被引用和修改所有两个
和所有三个
都在被修改,因为您直接分配了它们。我通过克隆对象修复了这一问题,但当您使用AJAX时,这可能不是问题。
这是您的小提琴的更新版本:在您的情况下,getObject()
是必需的,但为了简单起见,我在回答中排除了它。我知道您需要执行PUT/POST请求来更新服务器端的对象,但我认为根本没有必要将视图重新绑定到服务器响应。基本上,在大多数情况下,PUT不需要200 OK以外的响应。关键是你告诉服务器更新对象,而不是创建它们。因此,主键不会更改,因此,不需要重新绑定对象。更改已驻留在内存中
HTML
你的代码让我很困惑。为什么每次迭代for
循环时都要向服务器发布,并将视图绑定到其响应?我也不明白getObject()
的目的是什么。这个示例被简化了,但让我解释一下:getObject
根据当前的$index
(以及示例中未包含的其他值)从另一个数组中检索对象。请容忍我,忽略POST请求,您可以看到它在这里没有任何效果:。好的解决方案,但它可能有助于解释您为什么做出这些更改。当此解决方案与我提供的JS fiddle一起工作时,实际问题就是我在回复@Izzey时提到的问题。我同意@lzzey的解释,这就是您需要删除ng init的原因,但不需要解析和字符串化。parse(JSON.stringify(allTwo)):JSON.parse(JSON.stringify(allTwo));相反,您可以只使用angular.copy(),这将打破引用数据链。您完全正确,将所有发生的事件从{{obj}
更改为{{getObject(i)}
解决了我的问题。非常感谢你!!
$scope.changeType = function(ids, type) {
angular.forEach($scope.objects, function(o) {
if (ids.indexOf(o.id) > -1) {
o.type = type;
var response = (type === 2) ? allTwo : allThree
$scope.objects = angular.copy(response);
}
});
};
<div class="example" ng-controller="MyCtrl">
<div ng-repeat="obj in objects">
<div><pre>{{ obj }}</pre></div>
</div>
<a href="#" ng-click="changeType([1,2,3], 2)">Change all to Type 2</a>
<a href="#" ng-click="changeType([1,2,3], 3)">Change all to Type 3</a>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
// initial objects
$scope.objects = [
{ id: 1, type: 1 },
{ id: 2, type: 2 },
{ id: 3, type: 3 }
];
$scope.changeType = function(ids, type) {
angular.forEach($scope.objects, function(o) {
if (ids.indexOf(o.id) > -1) {
o.type = type;
// Perform your PUT/POST request here for each
// updated object to update it on the server-side.
// There is no need to bind to a server response.
}
});
};
}