【问题标题】:Put an index to a model with ng-options for a simple array使用 ng-options 为模型添加索引以获取简单数组
【发布时间】:2013-10-09 20:53:05
【问题描述】:

对于以下代码(见fiddle):

HTML:

<div ng-app ng-controller="MyCtrl">
    <select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>
    AM/PM: {{ampm}}
</div>

JS:

function MyCtrl($scope) {
    $scope.ampm = "AM";
} 

结果是,HTML:

<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']" class="ng-pristine ng-valid">
    <option value="0" selected="selected">AM</option>
    <option value="1">PM</option>
</select>

... 这很好。但是,'AM''PM' 被放入 ampm 模型中。是否可以将 0 或 1 之类的索引放入此模型中?我想要整数索引来引用数组中的位置,而不是需要重新计算的这个位置的值。

更新

有没有办法避免创建对数组?

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:

    您可以设置选择使用元素的索引作为模型。

    这使用 select as label for value in arrayng-options 语法,详见 Angular 文档:http://docs.angularjs.org/api/ng.directive:select

    我已经更新了 jsFiddle:

    http://jsfiddle.net/EyBVN/28/

    HTML:

    <div ng-app ng-controller="MyCtrl">
        <select 
        ng-model="ampm" 
        ng-options="options.indexOf(currOption) as currOption for currOption in options"></select>
        AM/PM: {{ampm}}
    </div>
    

    JS:

    function MyCtrl($scope) {
        $scope.options = ['AM', 'PM'];
        $scope.ampm = 0;
    }
    

    【讨论】:

      【解决方案2】:

      类似的东西?

      <div ng-app ng-controller="MyCtrl">
          <select ng-model="selectItem" ng-options="currOption as currOption.value for currOption in ampm"></select>
          AM/PM: {{selectItem.name}}
      </div>
      

      控制器

      function MyCtrl($scope) {
          $scope.ampm = [{name: "AM",value: "0" },{name: "PM",value: "1" }];
      
          $scope.selectItem = $scope.ampm[0];
      }
      

      演示Fiddle

      【讨论】:

      • 是的,这需要将数组转换为新的集合。我只是想知道我是否可以避免这种情况。
      • 编译后的 HTML 标记非常好。所以,数字作为值是可以的,我想让它们进入模型,而不是标题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多