I'm having trouble understanding why my Angular <select>
doesn't add the default value to the category I want.
I have an object that is returned from our database in Parse; the object is like this ( this is the "selected" option ):
$scope.item.category = { id: 'uosDHIF', className: 'Category', name: 'Projects' }
And I have a list of categories also:
$scope.categories = [{ id: 'uosDHIF', className: 'Category', name: 'Games' }, { id: 'uosDHIF', className: 'Category', name: 'Random' }, { id: 'uosDHIF', className: 'Category', name: 'Projects' }]
In my HTML what I have it's a select like this:
<select name="category" class="form-control mb-10" ng-model="item.category" ng-options="category.name for category in categories"></select>
I can select a new category and it's assigned to the item, and then I can save the item with item.save() but what I have trouble doing is that the selected (ng-model) doesn't seem to work, when I enter the page the first time I always get the default blank option even if I have the category when I check in the console.
Also, I was able to make it work with a simple object that I have created myself, but this object is returned from our database in Parse, so I'm not sure if this is the problem or I'm just missing something in there.
Thank you for your help.
Note: I have read other StackOverflow problems similar to mine but they doesn't help with mine.
In fact, on ng-options, you have to specify the value for the model (category as category.name => you choose category for ng-model but display it by his name).
The matching occurs by reference so you need the same object (category : $scope.categories[0]).
You can try:
JS
$scope.categories = [
{ id: 'uosDHIF', className: 'Category', name: 'Games' },
{ id: 'uosDHIF', className: 'Category', name: 'Random' },
{ id: 'uosDHIF', className: 'Category', name: 'Projects' }
];
$scope.item = {
category : $scope.categories[0]
};
HTML
<select name="category" class="form-control mb-10" ng-model="item.category" ng-options="category as category.name for category in categories"></select>