选择下拉默认值不起作用

时间:2018-03-19 12:56:56

标签: javascript html angularjs

我是网络开发的新手。在提出这个问题之前,我已经完成了所有的解决方案,但我仍然遇到了一些问题......

这里我有HTML:

<div class="col-md-6">
  <label class="col-sm-4 control-label agency-label" for="agency">Agency :</label>
  <div class="col-sm-4"> 
     <select id="selectAgency" 
        name="selectAgency" 
        class="selectpicker btn btn-labeled btn-start candidateAgencyPosition"  
        ng-init="candidate.agency = agency[0]"
        ng-model="candidate.agency"
        ng-options="agencies for agencies in agency">
        <!--<option value="">Select Your Option</option>-->
     </select>
  </div>
</div>

在这里我有一个数组:

$scope.agency = ["A", "B", "C", "D"];

现在我希望在该下拉列表中有一个A作为默认值。但目前我正在获得一个空值。

$scope.candidate = {
    noticePeriod: '',
    ctc: '',
    ectc: '',
    communication: '',
    agency: ''
};

这可能是重复但我遇到问题所以我问。感谢 帮助。

2 个答案:

答案 0 :(得分:2)

您应该在控制器中初始化ngModel链接变量,而不是使用ngInit

&#13;
&#13;
(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', ['$scope', function($scope) {
      $scope.agency = ["A", "B", "C", "D"];
      $scope.candidate = {
        agency: $scope.agency[0]
      };
    }]);
})(window.angular);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller">
    <select ng-model="candidate.agency" ng-options="agencies for agencies in agency"></select>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

删除ng-init并改为使用ng-model:

结果:

$scope.candidate = {
    noticePeriod: '',
    ctc: '',
    ectc: '',
    communication: '',
    agency: 'A'
  };