在Angular.js中使用PHP JSON数组作为ng-option


Use PHP JSON array as ng-option in Angular.js

我需要帮助与angular.js和php。我需要的选项被显示为一个选择下拉在我的角度视图,但由于某种原因,它只是不工作。我想我的json数据的格式是问题所在。请帮助。

JSON低于

{"states":{"1":"STATE 1","2":"STATE 2","3":"STATE 3"}}

下面的ANGULAR控制器

.controller('StateListController', function($scope, $http) {
        $scope.selectedState = null;
        $scope.options = [];
    $http.get('http://localhost/listStates.json').then(function(resp) {
        $scope.options = resp.data;
        console.log(resp.data);
    }, function(err) {
        console.error('ERR', err);
        // err.status will contain the status code
    })
})

下面的ANGULAR模板

<div class="list" ng-controller="StateListController">
  <label class="item item-input item-select">
      <div class="input-label">
          State
      </div>
      <select ng-model="selectedState" ng-options="state.id as state.name for state in options">
      </select>
  </label>
</div>

错误是您得到resp.data而不是resp.states。另外,这是不正确的:

state.id as state.name for state in options

,因为json 中的返回数据不像:

{"states":[{"id":"1", "name":"State 1"}, {"id":"2", "name":"State 2"}, {"id":"3", "name":"State 3"}]}

你需要做的是:

k as v for (k, v) in options

这是遍历对象属性的方法