1

I have the following data:

$scope.users = [
  {
    'id': 0,
    'name': 'Tom'
  },
  {
    'id': 1,
    'name': 'Jack'
  }
];

And I have a default object that is dynamically generated.

$scope.default = {
  'id': 1,
  'name': 'Jack'
}

I'm trying to set a default selected option in my ng-options based on $scope.default but because it's an object as opposed to a string, it doesn't seem to work.

<select ng-options="user.name for user in users" ng-model="default.name"></select>

I'm aware of this other question, but it doesn't work with objects.

how to use ng-option to set default value of select element

Community
  • 1
  • 1
trs
  • 863
  • 2
  • 16
  • 35
  • Use the ng-options syntax in one of the answers, then make a comparison in your controller between the default and the users and set the correct user index that matches the default. I think your issue is that you are trying to use the default object for the model instead of using it to identify the correct model. – Daniel Nalbach Jan 19 '16 at 19:36

3 Answers3

1

You can to use "as" and "track by" to define the label and the field to be compared:

<select ng-options="user as user.name for user in users track by user.id" ng-model="default"></select>

see the jsbin

Joao Polo
  • 2,153
  • 1
  • 17
  • 26
  • If you use ng-model directly on default.name, your "id" doesn't will change after the select, and could be confuse the result (an object with id from one value, and name from other value) – Joao Polo Jan 19 '16 at 19:30
  • I created a stripped down plnkr using your code, a much simpler example than I had before. Are you willing to take another look at it? Here is the new link: http://stackoverflow.com/questions/35142172/why-isnt-form-data-defined-in-this-re-usable-service – CodeMed Feb 02 '16 at 00:15
0

Check out https://docs.angularjs.org/api/ng/directive/ngInit

or try:

If it's dynamic ordering, then you could track by a custom field, user.orderNum or something you can alter. I haven't tested, but should get you in the right direction.

MichaelWClark
  • 382
  • 1
  • 12
  • I've tried ng-init but I can't seem to make it work either. Can you share an example? – trs Jan 19 '16 at 19:24
0

By default, ngModel watches the model by reference, not value. Try

<select ng-options="user.name for user in users track by user.name " ng-model="default.name"></select>.

More here

mallaudin
  • 4,744
  • 3
  • 36
  • 68