简体   繁体   中英

Can't access javascript-object properties via angularjs

I can't access javascript object properties within angularjs.

I have the following html to show a dropdown-list with all provinces loaded from angular 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 -->

The province object looks like this:

{"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"}}]}

Access {{selectedProvince.name}} or any other property is empty result aswell.

selectedProvince is defined in $scope!

Someone has any idea how i can access this data?

value="{{province}}" will not work properly because it will render your whole object as a string. For non-string values, you need to look at ng-options .

This should work for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM