在Angular JS的动态下拉菜单中选择默认值

时间:2018-10-09 10:29:03

标签: javascript angularjs

这是我的代码,这是什么地方

<select name="countryName" class="form-control" ng-model="twoFAData.country" style="height:35px">
  <option ng-repeat="country in contriesWithCode" value="{{country[2]}}" ng-selected="accountDetailsRes.country == country[2]">{{country[1]}} ({{country[0]}})</option>
</select>

在JS中,我定义了这个

$scope.defaultCountry = "USA";

$rootScope.accountDetailsRes = {country: $scope.defaultCountry, state: "selectstate"}; // its default country

预先感谢

2 个答案:

答案 0 :(得分:1)

首先,建议您在有许多下拉选项时使用ng-options而不是ng-repeat,因为它的效果更好。

<select ng-options="country[0] as country[0].concat(' ('+country[1]+')') for 
  country in contriesWithCode" ng-model="twoFAData.country" 
  name="countryName" class="form-control" style="height:35px">
</select>

然后,如果要使用默认值,只需设置$scope.twoFAData.country = 'USA'$scope.twoFAData.country = $scope.defaultCountry

app.controller('BaseController', function($scope) {
  $scope.defaultCountry = "USA";
  $scope.twoFAData = {};
  $scope.twoFAData.country = $scope.defaultCountry;
  $scope.contriesWithCode = [['USA', 'United States'], ['ARG', 'Argentina']];
});

答案 1 :(得分:0)

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {

    $scope.formData = {
        people : 2

    }
    $scope.people = [
        { id: 1, first: 'John', last: 'Rambo', actor: 'Silvester' },
        { id: 2, first: 'Rocky', last: 'Balboa', actor: 'Silvester' },
        { id: 3, first: 'John', last: 'Kimble', actor: 'Arnold' },
        { id: 4, first: 'Ben', last: 'Richards', actor: 'Arnold' }
    ];
    
    
  
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
              <select 
                ng-model="formData['people']">
              <option ng-repeat="item in people" value="{{item['id']}}">{{item['first']}}</option>

              </select>
{{people[formData['people']]['first']}}  {{people[formData['people']]['last']}} - {{people[formData['people']]['actor']}}
    </fieldset>
</div>