Search code examples
javascripthtmlarraysangularjsangular-ngmodel

value on select tag HTML convert array to string Javascript


I am using Javascript with Angular Js, In my controller I have the following Items :

$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"] }
  ];

In my view I am doing :

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

If I select an option, and then I do console.log(address.state) I get the object as an String instead of as array. How can I get the object as array (json).

The console output look like this :

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

I want to get the object as array, because then I do $Scope.address.state.city


Solution

  • Instead of doing an ng-repeat on the <option> tag you can do ng-options in the <select> tag:

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

    That way the object of state is passed into $scope.address and you can do $scope.address.state.cities

    Working example: https://plnkr.co/edit/k2gK5GNEt2xTrMbwih7V?p=preview