简体   繁体   中英

Angular ng-repeat vs ng-option

I am playing around with the dropdown menus using ng-options and ng-repeat in AngularJS. I have two menus here implemented differently.

Two questions: 1) why does this not work, can't select as expected 2) which way is better?

  <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>

in angular.js

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

Not sure exactly what you are asking, but I don't think you want $scope.sizes to be your model. So try something like this:

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

Controller:

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'];
}

As far as which is better ng-repeat or ng-options. Per the documentation here: 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."

Please use the following correction to view the select values

 <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>

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

About which is better, There is no performance penalty as such, you may choose to be consistent all across. Maybe some other SO User might shed some light.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM