javascript http调用后如何更新视图中的范围变量值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34017376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update scope variable value in view after http call?
提问by Deepu
I am making my first project using Angularjs 1.4.3.
我正在使用Angularjs 1.4.3制作我的第一个项目。
In my controller I am making a httprequest, in the successmethod of this http request I am updating a scope variable. In http call I am getting the latest values but in the view side its not updating the values.
在我的控制器中,我正在发出一个http请求,在这个 http 请求的成功方法中,我正在更新一个范围变量。在 http 调用中,我获得了最新值,但在视图端它没有更新值。
Plunker Link(@rupesh_padhye thanks). (Since it is calling the servlet action, so no data will be shown in Plunker)
Plunker 链接(@rupesh_padhye 谢谢)。(因为它调用的是servlet action,所以Plunker中不会显示任何数据)
app.controller('measuresCtrl', ['$scope', '$modal', '$http', function($scope, $modal, $http) {
$scope.groups = []
$scope.loadAllMeasure = function() {
$http.get("fetchAllMeasure")
.success(function(data) {
console.log("Before insert");
console.log($scope.groups);
$scope.groups = data.measures;
console.log("After insert");
console.log($scope.groups);
})
.error(function() {
});
};
$scope.loadAllMeasure();
$scope.submit = function (form) {
$http({
method: 'POST',
url: 'saveMeasure',
data: {
id: form.id,
name: form.name,
description: form.description
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
$scope.loadAllMeasure();
}).error(function(data, status, headers, config) {
});
}
})
})
And whenever I am performing any CRUD operation on measures I am calling a method $scope.loadAllMeasure();
. But its not updating the values in the view (jsp) page.
每当我对度量执行任何 CRUD 操作时,我都会调用一个方法$scope.loadAllMeasure();
。但它没有更新视图(jsp)页面中的值。
I have tried $scope.$applymethod but I am getting Error: $digest already in progress
.
我试过$scope.$apply方法,但我得到Error: $digest already in progress
.
When I printed the value for $scope.groupsusing console.loginside successmethod, then its showing the latest values.
当我在成功方法中使用console.log打印$scope.groups的值时,它会显示最新的值。
In my view (jsp) page I am just using ng-repeatfunction to show all the records in table format.
在我的视图 (jsp) 页面中,我只是使用ng-repeat函数以表格格式显示所有记录。
Code for my view page (minimal code) -
我的视图页面的代码(最小代码)-
<div ng-repeat="group in groups | orderBy:'name'">
<div>
<input type="checkbox" id="checkbox-{{group.id}}" class="ui-checkbox" /><label for="checkbox-{{group.id}}">{{group.name}}</label>
</div>
<div>{{ group.description}}</div>
<div>
<div class="fa fa-pencil button" data="{{group.id}}" id="{{::elementId}}" ng-click="showEditForm(group.id, $event)"></div>
<div class="fa fa-trash button" data="{{group.id}}" ng-click="deleteGroup(group.id)"></div>
<div class="fa fa-clone button" data="{{group.id}}" id="{{::elementId}}" ng-click="showCloneForm(group.id, $event)"></div>
</div>
</div>
Values in console.log are
console.log 中的值是
Before insert
Object { id=1, description="Measure Description1", name="Demo"}]
And
和
After Insert
[Object { id=1, description="Measure Description1", name="Demo"}, Object { id=2, description="Description2", name="Demo2"}]
How to update scope variable value in view after http call?
http调用后如何更新视图中的范围变量值?
回答by bradkt
After assigning the new data to a $scope variable call:
将新数据分配给 $scope 变量调用后:
$scope.$digest();
$scope.$digest();
This will update the current scopes values
这将更新当前范围值
reference here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope
参考这里:https: //docs.angularjs.org/api/ng/type/$rootScope.Scope
回答by Tjaart van der Walt
I cant see anything wrong with your example code.
我看不出你的示例代码有什么问题。
I have created a JSFiddle to try and help you.
我创建了一个 JSFiddle 来尝试帮助你。
The server call has been replaced by a setTimeout function that returns a promise.
服务器调用已被返回承诺的 setTimeout 函数取代。
Please see JSFiddle https://jsfiddle.net/sjwkbzxa/
请参阅 JSFiddle https://jsfiddle.net/sjwkbzxa/
Please see example below:
请看下面的例子:
<div data-ng-controller="TestController as vm">
<button data-ng-click="loadAllMeasure()">Load List from Server</button>
<ul>
<li data-ng-repeat="group in groups | orderBy:'name'">
<span>{{group.description}}</span>
</li>
</ul>
</div>
The javascript:
javascript:
angular.module('application',[]).controller("TestController", ['$scope', '$q', function($scope, $q){
$scope.groups = [{ id:1, description:"Initial List", name:"Demo"}];
$scope.loadAllMeasure = function(){
loadData().then(function(data){
$scope.groups = data;
});
};
function loadData(){
var deferred = $q.defer();
setTimeout(function(){
var data = [{ id:1, description:"Measure Description1", name:"Demo"}, { id:2, description:"Description2", name:"Demo2"}];
deferred.resolve(data);
}, 3000);
return deferred.promise;
}
}]);
Maybe you are missing something on your side that we cant see?
也许你错过了一些我们看不到的东西?
回答by AK23
I'm a little late to answer this, but here are my 2 cents:
我回答这个问题有点晚了,但这是我的 2 美分:
A simple assignment of the server data (response.data) to a $scope object didnt seem to work for me
将服务器数据 (response.data) 简单分配给 $scope 对象似乎对我不起作用
$scope.something = response.data //didn't work
So, I returned a promise object from the service into the controller and then use
所以,我从服务返回一个承诺对象到控制器中,然后使用
angular.copy(response.data,$scope.something)
to copy the values returned from the server. You could also pass the $scope.something to the service as a parameter to the function and have angular.copy in the service function as well, but i don't know if it's a good practise to do that.
复制从服务器返回的值。您还可以将 $scope.something 作为函数的参数传递给服务,并在服务函数中使用 angular.copy,但我不知道这样做是否是一个好习惯。
回答by Deepu
$scope.loadAllMeasure = function() {
CalltoServer();
};
CalltoServer = function() {
return $http.get("fetchAllMeasure")
.success(function(data) {
$scope.groups = data.measures;
})
.error(function() {
});
}
try this , the success will be after 2 or 3 seconds so i guess inside the event it takes rist to bind
试试这个,成功将在 2 或 3 秒后,所以我猜在事件内部需要 rist 绑定
回答by Abhishek Raj
Hey I also faced the same issue and if anyone is still looking, it is caused by change in the $scope variable inside the $http. I think a new $scope is being created inside the success function(some prototypical inheritance stuff). So make a copy of the variable $scope, something like
嘿,我也遇到了同样的问题,如果有人还在寻找,这是由 $http 中 $scope 变量的更改引起的。我认为在成功函数中创建了一个新的 $scope(一些原型继承的东西)。因此,复制变量 $scope,类似于
var s = $scope;
and then change
然后改变
s.groups = someData;
Your code:
您的代码:
app.controller('measuresCtrl', ['$scope', '$modal', '$http', function($scope, $modal, $http) {
var s = $scope;
$scope.groups = []
$scope.loadAllMeasure = function() {
$http.get("fetchAllMeasure")
.success(function(data) {
console.log("Before insert");
console.log($scope.groups);
s.groups = data.measures;
console.log("After insert");
console.log($scope.groups);
})
.error(function() {
});
};
$scope.loadAllMeasure();
$scope.submit = function (form) {
$http({
method: 'POST',
url: 'saveMeasure',
data: {
id: form.id,
name: form.name,
description: form.description
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
$scope.loadAllMeasure();
}).error(function(data, status, headers, config) {
});
}
})