1

I'm using angular chosen plugin for selecting an attribute on any select element.

My data is in this format:

 $scope.pets =  [
      {
          id: '1',
          name: 'Dog',
          desc:"Something"
      },
      {
          id: '2',
          name: 'Cat',
          desc:"Something"
      },
      {
          id: '3',
          name: 'Rat',
          desc:"Something"
      }
  ];

And the angular choosen implementation for displaying the name using ng-options is:

<select multiple ng-model="myPets"  ng-options="r as r.name for r in pets" chosen>

I'm able to get the drop down using ng-options for the above data like this,enter image description here

But how can I bind the default values into the angular choosen input box if my ng model is bind to the following object:

$scope.myPets= { id: '6', name: 'Pig', desc:"Something" },

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
forgottofly
  • 2,729
  • 11
  • 51
  • 93
  • possible duplicate of [How to have a default option in select box - Angular.js](http://stackoverflow.com/questions/18194255/how-to-have-a-default-option-in-select-box-angular-js) – Ivan Chernykh Oct 28 '14 at 06:05

1 Answers1

2

You can set the default values in the controller by using

$scope.myPets= [$scope.pets[0], $scope.pets[5]];

Compared to what you were thinking you need to use an array [] because you are using select multiple. You also have to directly refer to the existing objects or angular/javascript won't recognize the connection.

Absor
  • 536
  • 3
  • 7
  • Thanks @Absor.By default I need to bind dynamic values to $scope.myPets.How can this be done? – forgottofly Oct 28 '14 at 06:54
  • 1
    @MANOJ What do you mean by dynamic values? If it is, for example, data from an ajax call, you could just set `$scope.myPets` after setting `$scope.pets`. – Absor Oct 29 '14 at 10:11
  • Same as Ajax call the objects inside $scope.myPets will get changed because once you select an element and save the next time when you load the page the previously selected element should be listed in the model ie., $scope.myPets – forgottofly Oct 29 '14 at 11:05
  • Sounds like you have to store the selected value between page loads if you aren't yet (or at least the ids) and then return the stored values on page load to myPets. But I might have misunderstood. – Absor Oct 29 '14 at 11:18