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" },

1

1 Answer 1

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.

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

4 Comments

Thanks @Absor.By default I need to bind dynamic values to $scope.myPets.How can this be done?
@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.
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
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.

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.