1

I have a form with several hundred select elements. When the user saves the form I am saving off the JSON and when they reload it pulling it back down using a JS proxy. I am looking for a good / clean way for it to set the option value from the value in the JSON. Preferably without enumerating the array for each one of these and setting it based on the index where it matches the value.

jsfiddle

template:

<div ng-app="myApp">
<div ng-controller="myCtrl">
<select ng-model="jsModel.selVal"ng-options="myVal.value for myVal in myValArr"/>
</div>

app.js:

var myApp = angular.module('myApp',[]);

function myCtrl($scope) {
  $scope.myValArr = [{ value: 'Yes' }, { value: 'No' }]; 
  $scope.jsModel = ({ selVal: 'Yes' }); // Returned from proxy call
}

2 Answers 2

5

Demo

Here all you need to do is while working with ng-options It should match the selected object format with the deffault one.

<div ng-app="myApp">
<div ng-controller="myCtrl">
    <select ng-model="jsModel.selVal" ng-options="myVal.value as myVal.value for myVal in myValArr"/>
</div>

Check the ng-options in above template.For more details see the documentation of angular ng-options.

Your mistake : Your select element is setting whole object in ng-model and in default you are trying to set only value of your property.So both are not matching. Hope you understand or let me know.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thank you. I knew I needed to get at the property instead of the root of the object but wasn't finding anything in my searching on accomplishing this using the ng-options.
you can also use the whole object as the model, in this case you only have to add tracked by myVal.value at the end of ng-options.
0

Given your scope, something like this should work I'd imagine:

HTML

<select ng-model="jsModel.selVal">
    <option ng-repeat="val in myValArr" value="{{val.value}}">{{val.value}}</option>
</select>

For more advanced use cases take a look at ngOptions in combination with the select directive

1 Comment

It will work but let's give him solution of his problem. the way he did is also not wrong. only mistake is in syntax of ng-options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.