Buckwheat
Buckwheat

Reputation: 39

ng-options and ng-model preselected value

I'm trying to preselect value with ng-options. Here's what

 <select ng-model="promocode.PRODUCT" ng-change="getSomething()" ng-options="product as product.NAME for product in products">

The problem is in selected by default value. I have promocode.PRODUCT object the same as in ng-options, but angular set default value empty.

Where is my mistake?

Upvotes: 0

Views: 861

Answers (3)

Vinay
Vinay

Reputation: 558

Try this..

<select ng-model="promocode.PRODUCT"
    ng-change="getSomething()"
    ng-options="product as product.NAME for product in products track by product.ID">
    <option selected disabled>{{Your default value}}</option>
 </select>

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72849

Assuming your products have some kind of id property, this should do the trick:

 <select ng-model="promocode.PRODUCT"
    ng-change="getSomething()"
    ng-options="product as product.NAME for product in products track by product.id">

track by product.id tells angular to compare array items by their id property, instead of comparing equality between objects.

Here's some more info on tracking / ng-options.

And a working example:

var myApp = angular.module('myApp', []);
myApp.controller("controller", function($scope) {
  $scope.products = [{
    id: 1,
    name: 'FirstProduct'
  }, {
    id: 2,
    name: 'SecondProduct'
  }];

  $scope.promocode = {
    product: { // Here I am using a placeholder product to illustrate that 
      id: 2    // the select is identifying the correct row by it's `id`.
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="controller">
  <select ng-model="promocode.product" ng-change="getSomething()" ng-options="product as product.name for product in products track by product.id">
  </select>
  <br/>
  {{promocode.product}}
</div>

A better option would be to select the correct row, like this:

$scope.promocode = $scope.products[1];

Then you won't have to duplicate any data.

Upvotes: 2

Satpal
Satpal

Reputation: 133403

Assuming product has id property, You need to use select as label group by group for value in array track by trackexpr, Read DOCs

 <select ng-model="promocode.PRODUCT"
    ng-change="getSomething()"
    ng-options="product as product.NAME for product in products track by product.ID">
 </select>

jsFiddle

Upvotes: 1

Related Questions