0

From this example

I'm trying to set the select value from my controller and this doesn't work for me even when I set the id as explained in many questions here. The only difference is that I have a default value set with ng-init. How do I set the value from the controller?

DOM:

<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)">
    <option value="0">-- All orders --</option>
    <option ng-repeat="obj in orders" value="{{ obj.id }}">{{ obj.name }}</option>
</select>

JS inside a function:

$scope.orders = data;
$scope.storeorder = parseInt($scope.order); // Tried without parseInt also

console.log($scope.storeorder) returns the right value, but it doesn't set the right value in the browser DOM.

Community
  • 1
  • 1
Marc
  • 48
  • 1
  • 8

3 Answers3

2

If you don't want to use ng-options(which is the right way) , you can try with

ng-selected : Working Demo : http://jsfiddle.net/nf2m0rr1/

Example : 

 <body ng-app ng-controller="OrderCtrl">
   <div>Order is: {{storeorder}}</div>
   <select ng-model="storeorder">
     <option ng-selected="{{order.value == storeorder}}" ng-repeat="order in orders"   value="{{order.value}}">{{order.displayName}}</option>
   </select>
 </body>

 function OrderCtrl($scope) {
  $scope.storeorder = 2;

  $scope.orders = [{
    value: '1',
    displayName: 'Order One'
  }, {
    value: '2',
    displayName: 'Order Two'
  }]
}
Senthil
  • 946
  • 1
  • 14
  • 34
0

Use ng-options:

<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)" ng-options="obj.id as obj.name for obj in orders">
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

ng-options solved 50% of the problem but I still needed to handle the default value in the DOM and change the ng-init option. This was really bugging me. Here's the complete solution which enabled me to not set anything from the controller:

<select ng-model="storeorder" ng-options="orderdata.id as orderdata.name for orderdata in orders" ng-init="storeorder = order == 0 ? 0 : order" ng-if="orders.length > 0" ng-change="storeOrderChange(storeorder)">
    <option value="">-- All orders --</option>
</select>
Marc
  • 48
  • 1
  • 8