如何为 angular 选项设置默认值

how to set default value for angular chosen

我想将我的 angular 选择设置为我回复中的默认值。我的 Angular 选择的下拉值也来自 AJAX 响应。我尝试了 ng-init 并将值指向索引。但是运气不好。

HTML

   <select  ng-init="model.country = cities[currentLocationIdx]"  
chosen  ng-model="model.country"  
   ng-options=" cities.name for cities in cities" required> 
    <option value="">Select a Location</option> 
    </select>

JS:

$scope.model.country = "Bangalore";
    $scope.currentLocationIdx = $scope.cities.findIndex( city => city.name ===  $scope.model.country );

JSON:

[
  {
    "name": "South Andaman"
  },
  {
    "name": "Nicobar"
  },
  {
    "name": "Adilabad"
  },
  {
    "name": "Anantapur"
  },
  {
    "name": "Chittoor"
  },
  {
    "name": "East Godavari"
  },
  {
    "name": "Bangalore"
  }
]

试试下面更新的代码。它在我选择的库中工作。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
</head>
<body ng-app="app" ng-controller="ctrl">

    <select name="mySelect" id="mySelect" chosen
            ng-options="city.name for city in cities track by city.name"
            ng-model="country"></select>

    {{country}}

    <script src="../lib/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-chosen-localytics/1.8.0/angular-chosen.js"></script>
    <script>
        var app = angular.module('app', []);
        app.controller('ctrl', function ($scope) {

            $scope.cities = [
                  {
                      "name": "South Andaman"
                  },
                  {
                      "name": "Nicobar"
                  },
                  {
                      "name": "Adilabad"
                  },
                  {
                      "name": "Anantapur"
                  },
                  {
                      "name": "Chittoor"
                  },
                  {
                      "name": "East Godavari"
                  },
                  {
                      "name": "Bangalore"
                  }
            ];
            $scope.country = { "name": "Bangalore" };
        });
    </script>

</body>
</html>

您只需要像这样在控制器中将您的变量声明为 obj 即可:

$scope.model = {};

WORKING DEMO