使用ng-select将角度设置选项值作为数组迭代

时间:2015-06-29 09:59:18

标签: javascript arrays angularjs

来自控制器:

$scope.form_data = {
    day: 'Day'
};

$scope.days = [
    'Day',1,2,3,4,5,6,7,8,9,10,
    11,12,13,14,15,16,17,18,19,20,
    21,22,23,24,25,26,27,28,29,30,
    31
];

来自html:

<select ng-model="form_data.day" ng-options="day for day in days"></select>

结果是:

<select ng-options="day as day for day in days" ng-model="form_data.day" class="ng-pristine ng-valid ng-touched">
   <option value="string:Day" label="Day" selected="selected">Day</option>
   <option value="number:1" label="1">1</option>
   <option value="number:2" label="2">2</option>
....
</select>

哪个好..但我无法从文档中弄清楚如何将选项的值设置为数组键,即从上面的例子中,第一个选项的值我需要为0,即第一个POS机。在阵列中。

这是否可以使用ng-options?

2 个答案:

答案 0 :(得分:1)

是的,有可能,你几乎就在那里。

请参阅此帖子的第一个回复:Put an index to a model with ng-options for a simple array

您的选择应答:

<select 
        ng-model="form_data.day" 
        ng-options="days.indexOf(day) as day for day in days"></select>

我写了一个例子:https://jsfiddle.net/w7jdktxn/1/

答案 1 :(得分:0)

从未这样做过,但这就是你的要求!

        <div ng-init="days = [1,2,3,4,5]">
            <select ng-model="form_data.day" class="ng-pristine ng-valid ng-touched">
                <option value="" disabled selected style="display: none;">Select day</option>
                <option ng-repeat="day in days" value="{{$index}}" >{{day}}</option>
            </select>
            <h3>form_data.day={{form_data.day}}</h3>
        </div>