如何使用angular JS设置下拉列表控件的选定选项

the*_*mhz 138 selected angularjs drop-down-menu angular-ngmodel

我正在使用Angular JS,我需要使用angular JS设置下拉列表控件的选定选项.请原谅我,如果这很荒谬,但我是Angular JS的新手

这是我的html的下拉列表控件

 <select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
   ng-show="item.id==8" ng-model="item.selectedVariant" 
   ng-change="calculateServicesSubTotal(item)"
   ng-options="v.name for v in variants | filter:{type:2}">
  </select>
Run Code Online (Sandbox Code Playgroud)

填充后,我得到了

 <select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 &amp;&amp; item.quantity &gt; 0" class="ng-pristine ng-valid ng-valid-required">
    <option value="?" selected="selected"></option>
    <option value="0">set of 6 traits</option>
    <option value="1">5 complete sets</option>
</select>
Run Code Online (Sandbox Code Playgroud)

如何设置value="0"要选择的控件?

Ste*_*ers 190

我希望我理解你的问题,但是该ng-model指令在控件中的选定项和值之间创建了一个双向绑定item.selectedVariant.这意味着更改item.selectedVariantJavaScript或更改控件中的值会更新另一个.如果item.selectedVariant值为0,则应选择该项.

如果variants是对象数组,则item.selectedVariant必须将其设置为其中一个对象.我不知道您的范围中有哪些信息,但这是一个例子:

JS:

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
Run Code Online (Sandbox Code Playgroud)

HTML:

<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
Run Code Online (Sandbox Code Playgroud)

这将使"b"项目被选中.


jsm*_*lch 34

我不知道这是否会对任何人有所帮助,但是当我遇到同样的问题时,我想分享我是如何得到解决方案的.

您可以在自己的属性中使用track by属性ng-options.

假设你有:

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
Run Code Online (Sandbox Code Playgroud)

你可以提到你ng-options的:

ng-options="v.name for v in variants track by v.id"
Run Code Online (Sandbox Code Playgroud)

希望这有助于将来的某些人.


Tad*_*cik 7

如果为其指定值0,item.selectedVariant则应自动选择.查看http://docs.angularjs.org/api/ng.directive:select上的示例,默认情况下通过简单分配选择红色$scope.color='red'.

  • 你还可以粘贴匹配的HTML吗? (3认同)

Art*_*hur 7

我看到这里已经写好了答案,但有时以其他形式写相同可能会有所帮助

<div ng-app ng-controller="MyCtrl">
  <select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>

<script type='text/javascript'>
  function MyCtrl($scope) {
    $scope.organizations = ['a', 'b', 'c', 'd', 'e'];
    $scope.referral = {
      organization: $scope.organizations[2]
    };
  }
</script>
Run Code Online (Sandbox Code Playgroud)