javascript - AngularJS select seems to need to match on the same object to set the selected option -
i have asked question in post why angular select not setting select using saved answers.
this select:
<select ng-model="question.answer" ng-options="opt opt.value opt in question.options" />
the answer pkozlowski.opensource tothis stackoverflow post got me thinking value being set in ng-model
of select can't matching of values being passed options in ng-options
of select.
i created this jsfiddle should highlight issue. whenever answer changed answer object logged console. (note reason being logged twice in jsfiddle, it's being logged once when run same code locally on machine)
you can see when button pressed, answer logged out same object structure third option, but picklist set blank option.
output logged console after setting picklist third option:
answer is: picklisttest.js:25 object {id: 3, value: "three"}
output logged console after clicking "settothirdanswer" button:
answer is: picklisttest.js:25 object {id: 3, value: "three"}
it same structure, not same object. wondered if object in model has exactly same object 1 of options.
this second jsfiddle shows that case. button setting answer reference 1 of option objects.
so, i'm happy have found out why selects weren't setting selected value after page refresh, know (and must common use case):
if options objects , setting whole object ng-model
, how can use saved json re-render form without first doing processing on client side?
var json = question = { options: [ { id: 1, value: "one" }, { id: 2, value: "two" }, { id: 3, value: "three" } ], answer: { id: 3, value: "three" } };
because answer object , third value of options array aren't same object, can't represent reference in json (can you?).
the ng-options attribute has track by
expression you're talking about:
ng-options="opt opt.value opt in question.options track opt.id"
see updated fiddle: http://jsfiddle.net/ckleu/6/
Comments
Post a Comment