3

Does ngModel working differently for input type text and select? The select control is not selected to reflect the initial model value.

When I change the value of the select, input and currentUser.field change also, but if I change the value of input text to another key nothing happens to select.

{{currentUser.field}} // show correct field field key (number) val

// ng-model works => show correct field key (number) val
<input ng-model="currentUser.field" type="text" /> 

// <option value="?" selected="selected" label=""></option> is selected
<select ng-model="currentUser.field" 
   ng-options='item.key as item.value for item in currentUser.collections.field '>
</select>

// only works with input text and {{currentUser.field}}
 <button ng-click='currentUser.field = 305'>select field (int)</button>
 <button ng-click='currentUser.field = "305"'>select field (string)</button>
2
  • 1
    Is item.key a number or string? is currentUser.field a number or string? Commented Jun 16, 2015 at 16:24
  • I tried either way, intial item.key is (int) currentUser.field is (int) Commented Jun 16, 2015 at 16:28

1 Answer 1

7

Your code should just work unless you are setting a value to currentUser.field that is not in your options:

var app = angular.module('app', []);

app.controller('myController', function($scope) {
  $scope.currentUser = {
    collections: {
      field: [{
        key: '1',
        value: 'one'
      }, {
        key: '2',
        value: 'two'
      }, {
        key: '3',
        value: 'three'
      }]
    }
  };
  $scope.currentUser.field = "2";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
  <h3>expression</h3>
  {{currentUser.field}}
  
  <h3>input</h3>
  <input ng-model='currentUser.field' type='text'>
  
  <h3>select</h3>
  <select ng-model='currentUser.field' ng-options='item.key as item.value for item in currentUser.collections.field'></select>
  
  <h3>buttons</h3>
  <button ng-click='currentUser.field="305"'>305</button>
  <button ng-click='currentUser.field="1"'>1</button>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Yup 305 was not in the options and also in turns out that type is important "305" is will not work if item.key is (int) which it is in my case

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.