0

assume that this is my controller:

function MainController(someService) {
    var vm = this;
    // remote call to load items
    var vm.items = someService.loadItems();
    /*
    * item's are something like this:
    * [
    *       {
    *           "id" : 15,
    *           "topic" : "مرکز  شهید بلباسی",
    *           "default" : false
    *       }, {
    *           "id" : 14,
    *           "topic" : "مرکز  شهید کاوه",
    *           "default" : false
    *       }, {
    *           "id" : 13,
    *           "topic" : "مرکز  شهید زین الدین",
    *           "default" : false
    *       }, {
    *           "id" : 4,
    *           "topic" : "مرکز شهید حسین همدانی",
    *           "default" : true
    *       }
    *   ]
    */
}

and this is select tag:

<select ng-model="vm.searchFilter.itemId"
        ng-options="item.id as item.topic for item in vm.items">
    <option value=""></option>
</select>

now, i want to set selected option to item that it's default property is true and don't want to use ng-model of select tag for this purpose. how can i do that?

Rasool Ghafari
  • 4,128
  • 7
  • 44
  • 71

2 Answers2

0

You can try to pipe the options to a filter.

ng-options="item.id as item.topic for item in vm.items | filter:item.default=='true'"

Then you should get all options where the option is true.

Edit:

to set that option as default value you have to repeat with the option tag and use the ng-selected to set the default option. You can try something like that:

<option ng-repeat="item in vm.items" value="..." ng-selected="item.default == 'true'">Default options</option>
René Höhle
  • 26,716
  • 22
  • 73
  • 82
  • by this way only items that have `default` value `true` can shown in select, but i want to show all items and only automatically set selected option to item that `default` value of that is `true`, and user can change select value and select other option. – Rasool Ghafari Jan 05 '17 at 17:29
  • this is very good trick, and it's work when i remove `ng-model` from select, but i don't want to this. because `ng-model` and `ng-selected` make conflict. also check my update to question – Rasool Ghafari Jan 05 '17 at 18:01
0

To have an option by default, just make sure that particular option to be set in the ng-model of the select tag.

<select ng-model="defaultVal"
        ng-options="item.id as item.topic for item in vm.items">
    <option value=""></option>
</select>

And now select a default value in controller

$scope.defaultVal = items[3].id;
Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62