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.

3 Answers 3

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'
  }]
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're a genius - this solved all my problems. Thanks.
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">

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.