I have a question about setting ng-model in combination of chosen widget and AngularJS (see this video : https://www.youtube.com/watch?v=8ozyXwLzFYs)
What I would like to do is to set recipients to some values which would be preselected. Here is HTML and JS for this example (from the video)
<h1>Chosen</h1>
<select data-placeholder="Choose a Recipient" multiple class="span4 chzn-select" chosen
ng-model="recipients" ng-options="recipient.name for recipient in recipientsList">
</select>
<p ng-repeat="recipient in recipients"><strong>{{recipient.name}}</strong></p>
And JS in controller
$scope.recipientsList = [];
$scope.recipients = [];
$scope.fetchRecipients = function() {
$http.get($scope.url).then(function(result){
$scope.recipientsList = [
{"id":0, "name":"Recipient 0"},
{"id":1, "name":"Recipient 1"},
{"id":2, "name":"Recipient 2"},
{"id":3, "name":"Recipient 3"},
{"id":4, "name":"Recipient 4"},
{"id":5, "name":"Recipient 5"},
{"id":6, "name":"Recipient 6"},
{"id":7, "name":"Recipient 7"},
{"id":8, "name":"Recipient 8"},
{"id":9, "name":"Recipient 9"},
{"id":10, "name":"Recipient 10"}
];
$scope.recipients = [{"id":0, "name":"Recipient 0"},
{"id":1, "name":"Recipient 1"}];
});
}
$scope.fetchRecipients();
I tried a few combination but values in menu aren't preselected, although they are stored in recipients, because they are visible below the menu. You can see this example here: http://jsfiddle.net/YKZSw/8/
Thanks for your ansers.
Matej
AngularJS ngOptions attribute selects an element from the array provided as data source. In your case, the recipientsList array contains certain number of objects. Yet, the elements you wish to preselect are not present in the list due to object inequality even though they are similar. Meaning recipientsList: {"id":0, "name":"Recipient 0"} is not equal to recipients:{"id":0, "name":"Recipient 0"}(You can try the same in the JS console). Angular does not find the element in the list and hence does not preselect.
This modified fiddle works: http://jsfiddle.net/mananbharara/YKZSw/9/ The only difference in this case is in your recipients definition:
$scope.recipients = [$scope.recipientsList[0], $scope.recipientsList[1]];
In this case you have one list and selected values can come from that list only.
An alternative to this approach which you would use in case you have to maintain two lists is to keep the select value as a primitive type. In which case primitive equality would always hold.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With