如何设置所选角度的默认值

时间:2018-06-26 05:55:36

标签: angularjs angular-chosen

我想从响应中将角度选择为默认值。我的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"
  }
]

2 个答案:

答案 0 :(得分:1)

请尝试以下更新的代码。它在我选择的库中起作用。

<!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>

答案 1 :(得分:1)

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

$scope.model = {};

WORKING DEMO