how to set a default value for angular ui-select

praveenpds picture praveenpds · Dec 23, 2014 · Viewed 23.4k times · Source

Question :

how to set default value to the angular ui-select

drop down values are fetched from object and object wont be having default value.

and ui-select should set the default value in Frontend.

eg:

drop down values are as follows

1 -all fruits 2 -apple 3 -banana 4 -water melon

value from 2 to 4 are derived from object sent from server.but Frontend need to set default value ie 1 - all fruits

Referring to the below example set via ui-select2 how to migrate this in ui-select?

<select ng-model="fID" class="select"  ui-select2 data-placeholder="select fruit">
            <option value="">All fruits</option>
            <option ng-repeat="f in frits value="{{f.fID}}">{{f.name}}</option>
        </select>

<ui-select theme="select2" ng-model="fruits.selected">
            <ui-select-match placeholder="select please" allow-clear="false">                    {{$select.selected.name}}
</ui-select-match>
            <ui-select-choices repeat="f in fruits | filter:$select.search">
                <div ng-bind-html="f.name | highlight: $select.search:'underline'"></div>
            </ui-select-choices>
        </ui-select>

http://plnkr.co/edit/a3KlK8dKH3wwiiksDSn2?p=preview https://github.com/angular-ui/ui-select Link :angular-ui/ui-select

Answer

bahadir picture bahadir · Dec 23, 2014

you didnt use an id or something like that for option value so ui-select compares object address to understand if it is selected.

var p1 = { name: 'Adam',      email: '[email protected]',      age: 10 };
  $scope.person = {selected: p1};
  $scope.people = [
    p1,
    { name: 'Amalie',    email: '[email protected]',    age: 12 },
    { name: 'Wladimir',  email: '[email protected]',  age: 30 },
    { name: 'Samantha',  email: '[email protected]',  age: 31 },
    { name: 'Estefanía', email: 'estefaní[email protected]', age: 16 },
    { name: 'Natasha',   email: '[email protected]',   age: 54 },
    { name: 'Nicole',    email: '[email protected]',    age: 43 },
    { name: 'Adrian',    email: '[email protected]',    age: 21 }
  ];

change plunker like this and you will have a default selected value.

to set the default value on view you can use ng-init and set first object as selected