Reputation: 91969
My select
looks like
<select data-ng-model="transaction.category"
class="form-control"
data-ng-options="category.name group by category.parent for category in categories"
required>
</select>
The transaction
model looks like
$scope.transaction = {};
and I set values like
var transaction = new Transaction();
transaction.name = $scope.transaction.name;
transaction.category = $scope.transaction.category.uuid;
The categories
look like
[ {
name: Alcohol & Bars
parent: Food & Drink
uri: /categories/9b1e97f2-ac7d-4caf-85fc-476cd97dd6cb
uuid: 9b1e97f2-ac7d-4caf-85fc-476cd97dd6cb
} , {
name: Coffee & Tea
parent: Food & Drink
uri: /categories/cf040e77-2faa-41de-b9f7-3749a42735ac
uuid: cf040e77-2faa-41de-b9f7-3749a42735ac
} ...
]
When I select the value from drop-down everything works out fine
What is the problem then?
There are situations when I would like to set the category
based on some pre-populated user preference
What do I do then?
I do the following
$scope.templateSelected = undefined;
$scope.$watch('templateSelected', function () {
if ($scope.templateSelected !== undefined) {
$scope.transaction.category = $scope.templateSelected.category;
}
}, true);
and I expect that the values on HTML
select element will be selected. But this does not happens
Question?
How can I update my select option
based on $scope.templateSelected.category
?
UPDATE
The Transaction
looks like
angular.module('transactionService', ['ngResource']).factory('Transaction', function ($resource) {
return $resource('/user/transactions/:transactionId',
{transactionId: '@uuid'},
{
getRecent: {method: 'GET', params: {recent: true}, isArray: true},
getForYearMonth: {method: 'GET', params: {}, isArray: true}
});
});
Upvotes: 0
Views: 880
Reputation: 48972
By default, angular tracks selected value in <select>
based on object reference.
As you set $scope.transaction.category = $scope.templateSelected.category;
, the $scope.transaction.category
is not an object in the list.
You could ask angular to do identify selected value based on a property using track by category.uuid
:
data-ng-options="category.name group by category.parent for category in categories track by category.uuid"
Upvotes: 2