设置下拉列表的默认值并在AngularJS中重置它

时间:2018-04-17 11:52:37

标签: javascript jquery html angularjs

所以有一个下拉选择器必须在默认选项上设置,并且如果单击重置按钮,则可以重置为它。

我设法用jQuery做到了,我想知道如何使用AngularJS来完成



$('#buttonID').click(function(){
    $('#selectId').val('0');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="selectId">
    <option value="0">first option</option>
    <option value="1">second option</option>
    <option value="2">third option</option>
</select>
<input type="button" id="buttonID" value="reset"/>
&#13;
&#13;
&#13;

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您需要有一组选项和一个绑定到选择框的模型。重置时,您只需将绑定模型的值更改为您想要的值:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.opt = 0;
    $scope.options = [{
      value: 0,
      label: 'first option'
    }, {
      value: 1,
      label: 'second option'
    }, {
      value: 2,
      label: 'third option'
    }];
    
    $scope.reset = function() {
      $scope.opt = 0;
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select id="selectId" ng-options="opt.value as opt.label for opt in options" ng-model="opt">
</select>
  <input type="button" id="buttonID" value="reset" ng-click="reset()"/>
</div>