2016-01-24 82 views
0

我使用的Javascript角JS,在我的控制,我有以下項目:值轉換數組字符串的Javascript

$scope.address = []; 
$scope.states = [ 
    { name:"State 1", cities:[ "City Mexico 1", "City Mexico 2","City Mexico 3"] }, 
    { name:"State 2", cities:["City 1", "City 2", "City 3"] } 
    ]; 

在我看來,我做的:

<select ng-model="address.state" placeholder="Estado" > 
      <option ng-repeat="state in states" value="{{state}}"> {{state.name}}</option> 
      </select> 

如果我選擇一個選項,然後我做console.log(address.state)我得到的對象作爲一個字符串,而不是數組。我怎樣才能得到對象作爲數組(JSON)。

控制檯輸出是這樣的:

[state: "{"name":"State 1","cities":["City Mexico 1","City Mexico 2","City Mexico 3"]}"] 

我想要得到的對象數組,因爲那時候我做$ Scope.address.state.city

回答

0

而不是做對的ng-repeat<option>標籤,你可以在<select>標籤做ng-options

<select ng-model="address.state" ng-options="state.name for state in states" placeholder="Estados"></select> 

這樣,國家的目標是PA ssed爲$scope.address,你可以做$scope.address.state.cities

工作例如:https://plnkr.co/edit/k2gK5GNEt2xTrMbwih7V?p=preview

+0

它的作品!爲什麼ng-repeat不起作用? –

+0

當你通過'value =「{{state}}傳入時''你正在將該對象變成一個字符串,因爲」{{...}}「和'ng-options'是你傳遞的實際的對象 –