如何在Angular js中选择默认选项(india)?

时间:2017-03-14 13:42:15

标签: angularjs json

使用选择框显示国家/地区名称,选择来自外部json文件的选项。基于所选国家,我将状态json文件加载到另一个选择框中,直到每个东西都没问题,现在我需要将默认选择国家设置为INDIA,我尝试了以下代码。

HTML

<div ng-app="myApp" ng-controller="myCtrl">
    <div>
         <select id="country" ng-init="state1 = options['IN']" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)">
             <option ng-repeat="(key,country) in countries"  value="{{key}}">{{country[0]}}</option>
          </select>
    </div>{{countries}}{{state1}}    
    <div>
         <select id="state" ng-model="cities">
             <option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
         </select>
    </div>
</div>

脚本

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.states =  {
     "IN":[
       "Delhi",
       "Goa",
       "Gujarat",
       "Himachal Pradesh",
     ]
   };
   $scope.countries =  {
      IN: ["India"],
       ZA: ["South Africa"],
       AT: ["Austria"]
     }
    $scope.lastName = "Doe";
});

jsfiddle

1 个答案:

答案 0 :(得分:0)

在定义$scope.countries

后,在控制器中添加此项
$scope.state1 = Object.keys($scope.countries)[0];

从Html页面中删除ng-init