无法通过 angularjs 访问 javascript-object 属性

Can't access javascript-object properties via angularjs

本文关键字:访问 javascript-object 属性 angularjs      更新时间:2023-09-26

我无法访问angularjs中的javascript对象属性。

我有以下 html 来显示一个下拉列表,其中包含从角度 http-call 加载的所有省份:

$http.get("http://myRestUrl/province").then(function(response)
{
  $scope.provinces = angular.fromJson(response.data);
});
<select class="form-control" ng-model="selectedProvince">
  <option value="" selected>Bundesland auswählen</option>
  <option ng-repeat="province in provinces" value="{{province}}">
    {{province.name}}
  </option>
</select>
{{selectedProvince}} <!-- Output the Object -->
{{selectedProvince.cities}} <!-- Output nothing -->

省份对象如下所示:

{"id":1,"name":"North Rhine-Westphalia","nation":{"id":1,"name":"Germany"},"cities":
[{"id":1,"name":"Münster","province":{"id":1,"name":"North Rhine-Westphalia"}},
{"id":2,"name":"Rinkerode", "province":{"id":1,"name":"North Rhine-Westphalia"}}]}

访问{{selectedProvince.name}}或任何其他属性也是空结果。

选择省份在$scope中定义!

有人知道我如何访问这些数据吗?

value="{{province}}"将无法正常工作,因为它会将整个对象呈现为字符串。对于非字符串值,您需要查看ng-options

这应该适合您:

<select class="form-control" ng-model="selectedProvince"
  ng-options="province.name for province in provinces">
  <option value="" selected>Bundesland auswählen</option>
</select>