2016-01-21 95 views
0

我無法訪問angularjs中的javascript對象屬性。無法通過angularjs訪問javascript對象屬性

我有以下的HTML顯示一個下拉列表與角HTTP調用加載所有省份:

$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}}或任何其他財產也是空的結果。

selectedProvince在$ scope中定義!

有人有任何想法如何我可以訪問這些數據?

+1

想這是因爲你的HTTP調用。它返回一個承諾。在你的HTTP響應中使用'.then()'可能會解決你的問題,但我不完全確定是誠實的。只是值得一試。 – Aer0

+0

你的'selectedProvince'是一個字符串嗎? 'JSON.parse(selectedProvince)'然後允許你訪問屬性嗎? –

+0

'value =「{{province}}」'將無法正常工作,因爲它會將整個對象渲染爲一個字符串。看看['ng-options'](https://docs.angularjs.org/api/ng/directive/ngOptions) – Rhumborl

回答

0

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>