简体   繁体   中英

Set default selected in dropdown while binding Key-Value pair Object in AngularJs

I have a JavaScript Object in the following form, ( Plnkr )

{
  "1" : "John",
  "2" : "Jane",
   .
   .  //Continues.
}

I'm binding this Object to a dropdown using AngularJs, here is the html code

<select ng-model="CurrentName" ng-options="key as value for(key , value) in Names"></select>

And here is the Controller code

NamesScript.controller('NamesDropDown', function($scope) {
    var Data = Result.Data;  //This is a Parent Object I'm getting from a REST call. This contains the names Object.
    $scope.Names = Data.names;
    $scope.CurrentName = Data.CurrentName; //Yes getting the CurrentName separately it's NOT present in the Names Object.
//CurrentName Object is in this form {"7":"Foo"}

  }

I'm getting the DropDown properly populated except that the default is always blank. How do I set the default value equal to the one I'm getting in CurrentName object? Thanks.

check my plnkr i have a sample example for this. you need to specify value key in your controller

HTML

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    <script src="script.js"></script>

  </head>
  <body>

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

</div>


  </body>
</html>

Script.js

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM