1

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!

1

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.