How to initialize a select value when option is in ng-repeat?


At first I tried <select name='size' ng-model='sid' ng-options=' as y.title for y in arr'>. But when the form was submitted, the posted variable size is not the id 472 473 474 but the index 0 1 2.

Then I tried ng-options='y.title for y in arr track by'. But the selected model sid is not 473 but {"id":473,"title":"bb"} so I can't make that 473 item as default by ng-init='sid = 473'.

At last, I have to use option ng-repeat='y in arr' as below. But it seems that ng-init is useless, because it will initialize before the options repeat. How can I make it work?


<div ng-controller="Ctrl">
    <select ng-model='sid' ng-init='sid = 473'>
        <option ng-repeat='y in arr' value='{{ }}'>
            {{' - '+y.title }}
    {{ sid }}
    <button ng-click='sid=474'>change to 474</button>
var app =angular.module('app', []);

function Ctrl($scope){
    $scope.arr = [{"id":472,"title":"aa"},{"id":473,"title":"bb"},{"id":474,"title":"cc"}];

Problem courtesy of: harrrrrrry


Remember to read the docs:

"Do not use select as and track by in the same expression. They are not designed to work together."

All you needed was to fix up your ng-options:

<div ng-controller="Ctrl">
    <select ng-init="sid = 473" ng-model='sid'
      ng-options=" as ( + ' - ' + y.title) for y in arr">
    <input type="hidden" name="size" value="{{sid}}"/>
    {{ sid }}
    <button ng-click='sid=474'>change to 474</button>
Solution courtesy of: HankScorpio


Using a invisible input <input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

I found a solution but its not ideal. Welcome anyone who has a good idea to share.

Discussion courtesy of: harrrrrrry

This recipe can be found in it's original form on Stack Over Flow.