Angular ng-repeat 与 ng-option

Angular ng-repeat vs ng-option

我正在 AngularJS 中使用 ng-options 和 ng-repeat 来调整下拉菜单。我这里有两个菜单,实现方式不同。

两个问题: 1) 为什么这不起作用,不能按预期 select 2) 哪种方式更好?

  <body ng-controller="appController" class="container-fluid">
    <form>
      <label for="sizes"> Select size: </label>
       <select name= "sizes" id= "sizes" ng-model="sizes">
         <option ng-repeat="size in sizes" value="{{size}}"></option>
       </select> 

      <br>

      <label for="sizes"> Select size: </label>
      <select name = "sizes" id = "sizes" ng-model="sizes" ng-options="item for item in sizes track by item">
        <option value="{{size}}"></option>
      </select>
    </form>
  </body>

在angular.js

app.controller('appController', function($scope) {
    $scope.sizes = ['big', 'medium', 'small'];
}

请使用以下更正来查看 select 值

 <form>
      <label for="sizes"> Select size: </label>
       <select name= "selectSizes" id= "selectSizes" ng-model="sizes" >
        <option ng-repeat="size in sizes" value="{{size}}">**{{size}}**</option>
       </select> 

      <br>

      <label for="sizes"> Select size: </label>
      <select name = "sizes" id = "sizes" ng-model="sizes" ng-options="item for item in sizes track by item">
        <option value="{{size}}">**{{size}}**</option>
      </select>
    </form>

http://plnkr.co/edit/SDNrwpcu6E94VSVv3sWR?p=preview

测试

关于哪个更好,没有性能损失,您可以选择始终保持一致。也许其他一些 SO 用户可能会有所启发。

不确定您到底在问什么,但我认为您不希望 $scope.sizes 成为您的模型。所以尝试这样的事情:

<select ng-model="pickedSize.size" ng-options="size for size in sizes">
    <option value="">Pick a size...</option>
</select>

控制器:

app.controller('appController', function($scope) {
    //to demonstrate setting a model...can do this various ways.
    $scope.pickedSize={};
    $scope.pickedSize.size='';

    $scope.sizes = ['big', 'medium', 'small'];
}

至于哪个更好 ng-repeat 或 ng-options。根据此处的文档:https://docs.angularjs.org/api/ng/directive/select

"In many cases, ngRepeat can be used on elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits, such as more flexibility in how the 's model is assigned via the select as part of the comprehension expression, and additionally in reducing memory and increasing speed by not creating a new scope for each repeated instance."