AngularJS:从http GET(来自REST服务)检索到的JSON数据中显示一个选择框

AngularJS: display a select box from JSON data retrieved by http GET (from REST service)

本文关键字:数据 JSON 显示 一个 选择 检索 http GET 来自 AngularJS 服务      更新时间:2023-09-26

我有一个REST服务,它返回一个json字符串,该字符串只是一组字符串(我使用Gson生成这个字符串(Gson.toJson(mySetOfStrings))

所以我添加到我的index.html:

<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>

在我的脚本中:

var ListOptionsCtrl = function ListOptionsCtrl($scope, $http) {
  $scope.refreshList = function() {
    $http({ 
      method: 'GET'
      url: '*someurl*'
    }).
      success(function(data) {
        $scope.optionsList = angular.fromJson(data);
    });
  };
}

不幸的是,在我的选择框中产生的所有这些都是一个空列表。当我看到对GET请求的响应是什么时,它会返回一个包含内容的json字符串,所以我不明白为什么没有向这个元素添加任何内容。我在这里做错了什么?感谢

这是因为Angular还不知道您的更改。因为Angular允许将任何值用作绑定目标。然后,在任何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);
        });
    });
  };
}

试试这个。

关于它如何工作以及为什么需要它的更多信息,请访问Jim Hoskins的文章

在执行$apply之前,您应该执行if(!$scope.$$phase){…}来检查$digest错误。

success(function(data) {
     if(!$scope.$$phase) {
        $scope.$apply(function () {
            $scope.optionsList = angular.fromJson(data);
        });
      }
    });