AngularJS ui-select dropdown default value
Asked Answered
D

1

14

I am using angular ui-select for drop down. How can I set a default value for the drop down value?

<h3>Selectize theme</h3>
  <p>Selected: {{country.selected}}</p>
  <ui-select ng-model="country.selected" theme="selectize" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select or search a country in the list...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="country in countries | filter: $select.search">
      <span ng-bind-html="country.name | highlight: $select.search"></span>
      <small ng-bind-html="country.code | highlight: $select.search"></small>
    </ui-select-choices>
  </ui-select>

The snippet is from plnkr.co. Currently the dropdown just sowing default Select or search a country in the list... But i need to pass a value from controller. Lets say $scope.default = {"name":"Decard"}

Thanks!!

EDIT

This question is similar to This one but involving json return format of data.

Doublestop answered 7/10, 2015 at 3:2 Comment(0)
G
34

You can initial your ng-model to the default country object in your controller as following:

 $scope.country = {};
 $scope.country.selected = {name: 'Albania', code: 'AL'};

Then use "ui-select-match" to set the default value like this:

<ui-select ng-model="country.selected" theme="selectize" ng-disabled="disabled" style="width: 300px;">
<ui-select-match placeholder="Select or search a country in the list...">{{ $select.selected.name }}</ui-select-match>
<ui-select-choices repeat="country in countries | filter: $select.search">
  <span ng-bind-html="country.name | highlight: $select.search"></span>
  <small ng-bind-html="country.code | highlight: $select.search"></small>
</ui-select-choices>
</ui-select>

Gonagle answered 7/10, 2015 at 3:21 Comment(7)
console giving out this error Cannot set property 'selected' of undefinedDoublestop
make sure u have defined the country in your controller before : $scope.country = {};Gonagle
Ok, now the default is just empty.Doublestop
Thanks.. I mistakenly set wrong variable name. Now it worksDoublestop
That's great.. Sure thing!Gonagle
What if your ng-model is bound to the ID only, but the dropdown is an object ?Trapper
@Trapper I don't now if this is the best solution, but you can use $filter to find the object with the desired ID (assuming the ID is a property of the object). Keep in mind that $filter returns an array, so if the ID is unique, just add [0] to the end of the filter definitions to get the first (and only) result.Hibernate

© 2022 - 2024 — McMap. All rights reserved.