爲Angularjs ngOptions加上index解決方案

今天在Angularjs交流羣中有位童學問道如何爲Angular select的ngOptions像Angularjs的ngRepeat一樣加上一個索引$index.

其實對於這個問題來說Angular本身並未提供$index之類的變量供使用。但是也不是說對於這個問題我們就沒有解決方案。

把這個問題換成角度來看,我們所需要的就是js數組的下標,所以我們如果我們能夠在對象上加入下標,使用表達式作爲option的label就能解決了。

但是第一印象讓我想起的是js數組本來就是一個key/value的對象,只是key爲數組下標而已,所以有了如下之設計:

html:

<pre></pre><select  ng-model="a" ng-options="value.field as getDesc1(key,value) for (key,value) in t"></select>

js:

$scope.getDesc1 = function(key, value) {
    return (parseInt(key, 10) + 1) + "->" + value.field;
};

可是不幸的是如果對於JavaScript你若將他作爲key/value對象那麼key將是無序的所以,出現了無序的下標如下:

<select ng-model="a" ng-options="l.field as getDesc1(key,value) for (key,value) in t " class="ng-valid ng-dirty">
  <option value="0"  >1-&gt;jw_companyTalent</option>
  <option value="1"  >2-&gt;jw_reportgroup</option>
  <option value="10" >11-&gt;jw_ads</option>
  <option value="11" >12-&gt;jw_jobcomment</option>
  <option value="12" >13-&gt;jw_companyInfo</option>
  ....
</select>

所以這樣是無法解決的。還好博主還有一招,ngOptions支持Angularjs的filter,所以我們可以對數據源對象上加上一個order字段標示下標作爲序號。並且你可以在一個2年前的Angular的issue中看到Angular已經fix issue,option會對數組進行按下標順序生成。

html:

<pre></pre>
<select  ng-model="b" ng-options="l.field as getDesc(l) for l in t | index "></select>

js:

var app = angular.module('plunker', []);
   app.controller('MainCtrl', function($scope) {
     $scope.t = [{
       "field": "jw_companyTalent"
     }, {
       "field": "jw_reportgroup"
     }];
     $scope.getDesc = function(l) {
       return l.order + "->" + l.field;
     };
   }).filter("index", [
     function() {
       return function(array) {
         return (array || []).map(function(item, index) {
           item.order = index + 1;
           return item;
         });
       };
     }
   ]);

這下option是按照有序的生成,最後我們終於能完美解決了,所以本文也將收尾。在最後在附上可運行的demo plnkr ngOptions index;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章