Javascript AngularJS:从http GET(从REST服务)检索的JSON数据中显示一个选择框
我创建了一个REST服务,它返回一个json字符串,它只是一组字符串(我使用Gson生成这个字符串(Gson.toJson(mySetOfStrings)) 因此,我在index.html中添加了:Javascript AngularJS:从http GET(从REST服务)检索的JSON数据中显示一个选择框,javascript,html,json,rest,angularjs,Javascript,Html,Json,Rest,Angularjs,我创建了一个REST服务,它返回一个json字符串,它只是一组字符串(我使用Gson生成这个字符串(Gson.toJson(mySetOfStrings)) 因此,我在index.html中添加了: <div ng-controller="ListOptionsCtrl"> <form novalidate> <button ng-click="refreshList()">refresh</button> <select
<div ng-controller="ListOptionsCtrl">
<form novalidate>
<button ng-click="refreshList()">refresh</button>
<select name="option" ng-model="form.option" ng-options="o.n for o in optionsList></select>
</form>
</div>
不幸的是,在我的选择框中产生的所有这些都是一个空列表。当我看到GET请求的响应是什么时,它返回一个包含内容的json字符串,因此我不知道为什么没有向该元素添加任何内容。我在这里做错了什么?谢谢,这是因为Angular还不知道您的更改。因为Angular允许ny值用作绑定目标。然后在任何JavaScript代码转换结束时,检查该值是否已更改 您需要使用$apply
var ListOptionsCtrl = function ListOptionsCtrl($scope, $http) {
$scope.refreshList = function() {
$http({
method: 'GET'
url: '*someurl*'
}).
success(function(data) {
$scope.$apply(function () {
$scope.optionsList = angular.fromJson(data);
});
});
};
}
试试这个
更多关于它如何工作以及为什么需要它的信息,请参见在执行$apply之前,您应该通过执行if(!$scope.$$phase){…}检查$digest错误
success(function(data) {
if(!$scope.$$phase) {
$scope.$apply(function () {
$scope.optionsList = angular.fromJson(data);
});
}
});
您应该使用
ngResource
。Angular将自动为您解析JSON。注意,如果JSON是一个列表,您将使用.query()
^同意。只需设置optionsList=data;如果不起作用,我们需要查看JSON对象的外观。您能提供JSON数组结构吗?我相信$http handles$apply()自动。将$scope.$apply()置于$htpp内将抛出“$digest ready in progress”错误。
success(function(data) {
if(!$scope.$$phase) {
$scope.$apply(function () {
$scope.optionsList = angular.fromJson(data);
});
}
});