Reputation: 581
I am attempting to get a JSON encoded response from an AJAX request into a select statement using angular ng-options. I do not have control of the PHP source of where the JSON response comes from.
The response is in the form:
{"A":"Col1","B":"Col2","C":"Col3","D":"Col4"}
I am using a simple select dropdown and need to populate the above JSON utilizing the index set as the value and the value set as the dropdown text. Example below.
<select ng-model="selectedItem" ng-options="item for item in items">
Options should result in this:
<option value="A">Col1</option>
<option value="B">Col2</option>
<option value="C">Col3</option>
...
I am unsure what I am missing for the format of the JSON response so it'll be used in the ng-options. I've tried all forms of the ng-options to no avail. I've also tried to format the response with json.parse, json.stringify, .eval(), etc.
Upvotes: 0
Views: 4352
Reputation: 581
Considering the json_encoded array was a correct object when it hit the angular function, I was able to get this working just by keeping it an object and manipulating the ng-options with a key, value configuration. Code below.
<select ng-options="k as v for (k, v) in cols"></select>
I referenced the post here: ng-options with object data source
This worked out because I don't have control over the json encoded array coming to my controller but I needed to reference the key as the value for the options of the select instead of letting angular let it do its own thing with it.
Upvotes: 3
Reputation: 1940
use the angular JSON parser build in function: $scope.items = angular.fromJson(myJSON)
https://docs.angularjs.org/api/ng/function/angular.fromJson
Upvotes: 0