João Paiva João Paiva - 3 months ago 10
JSON Question

Why does ng-model in a select return string and not JSON?

I have the following code:

<select class="form-control" id="existing-phases" ng-model="selectedPhase">
<option disabled selected value>-- select an option --</option>
<option ng-repeat="p in existingPhases" value="{{p}}">{{ p.Name }</option>
</select>


When I select an option in my select I was hoping to get the JSON corresponding to the selected phase which should be like this:

{"ID":2,"Name":"Outlook"}


However, I'm getting the JSON as a string for some reason:

"{\"ID\":2,\"Name\":\"Outlook\"}"


How can I make it so that the ng-model returns the JSON and not a string?

P.S.: I don't want to convert it afterwards in a method, because I know that you can do that with JSON.Parse().

Update:

Debug print:

enter image description here

Answer

I setup a plunker with you code and seems to work normally

https://plnkr.co/edit/Q8Cmknqg8bGBc5hABtF1

<!DOCTYPE html>
<html>
  <head>
    <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
    <script>
      angular.module('app', [])
      .controller('FooCtrl', function($scope) {
        $scope.existingPhases = [
          {"ID":1,"Name":"a"},
          {"ID":2,"Name":"b"},
          {"ID":3,"Name":"c"},
          {"ID":4,"Name":"d"},
          {"ID":5,"Name":"e"}];
        $scope.selectedPhase;
      });
    </script>
  </head>
  <body ng-app="app">
    <div ng-controller="FooCtrl">
      <select id="existing-phases" ng-model="selectedPhase">
        <option disabled selected value>-- select an option --</option>
        <option ng-repeat="p in existingPhases" value="{{p}}">{{ p.Name }}</option>
      </select>
      {{selectedPhase}}
    </div>
  </body>
</html>

please check your code I don't think it's an select directive problem

Comments