francoisromain francoisromain - 5 months ago 28
AngularJS Question

how to use ng-option to set default value of select element

I've seen the documentation of the Angular select directive here: http://docs.angularjs.org/api/ng.directive:select.
I can't figure how to set the default value. This is confusing me:


select as label for value in array


Here is the object:

{
"type": "select",
"name": "Service",
"value": "Service 3",
"values": [ "Service 1", "Service 2", "Service 3", "Service 4"]
}


The html (working):

<select><option ng-repeat="value in prop.values">{{value}}</option></select>


and then I'm trying to add an ng-option attribute inside the select element to set
prop.value
as the default option (not working).

ng-options="(prop.value) for v in prop.values"


What am i doing wrong?

Answer

So assuming that object is in your scope:

<div ng-controller="MyCtrl">
  <select ng-model="prop.value" ng-options="v for v in prop.values">
  </select>
</div>

 

function MyCtrl($scope) {
  $scope.prop = {
    "type": "select", 
    "name": "Service",
    "value": "Service 3", 
    "values": [ "Service 1", "Service 2", "Service 3", "Service 4"] 
  };
}

Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g

Comments