3

At first I tried <select name='size' ng-model='sid' ng-options='y.id 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 y.id'. 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?

Thanks.

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

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

http://jsfiddle.net/hcLVE/86/

isherwood
  • 58,414
  • 16
  • 114
  • 157
harrrrrrry
  • 13,643
  • 2
  • 23
  • 28

2 Answers2

1

Remember to read the docs:

"Do not use select as and track by in the same expression. They are not designed to work together." https://docs.angularjs.org/api/ng/directive/ngOptions

http://jsfiddle.net/qm7f2kqj/

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

<div ng-controller="Ctrl">
    <select ng-init="sid = 473" ng-model='sid'
      ng-options="y.id as ( y.id + ' - ' + y.title) for y in arr">
    </select>
    <input type="hidden" name="size" value="{{sid}}"/>
    {{ sid }}
    <button ng-click='sid=474'>change to 474</button>
</div>
HankScorpio
  • 3,612
  • 15
  • 27
  • Thanks but this does not solve the question. This is what I tried at first! I know `select as` and `track by` cant be used in the same expression. – harrrrrrry Mar 10 '15 at 19:25
  • Have you tried the fiddle? It seems to work for me, or else I have misunderstood the question. What's missing? – HankScorpio Mar 10 '15 at 19:31
  • In this way, when the form was submitted, the posted variable size is not the id 472 473 474 but the index 0 1 2. – harrrrrrry Mar 10 '15 at 19:36
  • It sounds like you're doing it in a non-angular way. Ideally you'd be making a POST/GET from an angular service using the ng-model value, but since you're not I've updated my answer, and the jsFiddle with an alternative solution. – HankScorpio Mar 10 '15 at 19:48
  • Great. It is a good answer, better than my answer which uses a new input with the same ng-model. Thanks. – harrrrrrry Mar 10 '15 at 19:55
0

https://stackoverflow.com/a/18502634/3657140

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.

Community
  • 1
  • 1
harrrrrrry
  • 13,643
  • 2
  • 23
  • 28