Search code examples
angularjsng-options

How bydefault select an Item in - ng-repeat on options through use of model


I am using ng-repeat on option in select.

<select ng-model="mymodel">
        <option  ng-repeat="p in persons" value="{{p.id}}">{{p.name}}</option>
</select>

$scope.persons= [ {id:1,name:"tester11"}, {id:2,name:'tester22'}, {id:3,name:'tester33'}, {id:4,name:'tester44'} ];

How can I make an option selectable means by default "tester33" should be selected through use of ng-model.

I know it is achievable through ng-options. But I want to try this one.

Thanks in advance.


Solution

  • There is no perfect way to achieve this using ng-repeat, but here's a workaround:

    <select ng-model="mymodel">
        <option ng-repeat="p in persons" ng-selected="p.name=='tester33'" value="{{p.id}}">{{p.name}}</option>
    </select>
    

    This just sets the option with name='tester33' but the model won't get updated until the user changes select value explicitly

    NOTE: This is not a recommended way, you must use ng-options for complete functionality