Reputation: 962
I seem to have trouble setting a default value for a select dropdown with AngularJS. I have read similiar topics on StackOverflow, but none of the proposed solutions worked for me, so I decided to finally ask you guys :)
Bascically I want to implement an entry editing functionality in my app. So, the user clicks on the edit button, a modal pops up with a form with values filled from the object that was passed to the modal controller. I mean all of the values, but the "category" which I want to be presented as a dropdown select.
I think it's going to be easier to show in code, so I prepared this fiddle:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.dataReceived = {
category: "FOOD"
}
$scope.availableCategories = {
FOOD: "Food and drinks",
FREE_TIME: "Free time",
HOUSING: "Housing costs"
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="form-group">
<label for="select-category">Select category:</label>
<select class="form-control" id="select-category" ng-model="dataReceived.category" required>
<option ng-repeat="(key,value) in availableCategories" ng-value="key">
{{value}}
</option>
</select>
</div>
</div>
I tried different ways of fixing it, but none have worked so far so please help! All I want to do is for the dropdown to say "Food and drinks" by default if passed object's category is "FOOD". Cheers!
Upvotes: 1
Views: 33
Reputation: 1561
I think you should try to use ng-options with key value pairs instead.
Like this:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.dataReceived = {
category: "FOOD"
}
$scope.availableCategories = {
FOOD: "Food and drinks",
FREE_TIME: "Free time",
HOUSING: "Housing costs"
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="form-group">
<label for="select-category">Select category:</label>
<select class="form-control" id="select-category" ng-model="dataReceived.category" ng-options="key as value for (key , value) in availableCategories " required>
</select>
</div>
</div>
Hope it helps.
Upvotes: 1