【經驗】angularjs 實現帶查找篩選功能的select下拉框


一.背景

 


 

對於select的下拉列表,像國家選擇這樣的功能,全世界那么多國家,一直拉滾動條多辛苦,眼睛也要盯着找,累!so,為優化用戶體驗,帶查找功能的下拉框是非常非常有必要的。都知道jquery里有這樣的插件,但我們用的是Angularjs,更希望用雙向綁定,指令的方式優雅地解決這個問題。

分析:

   目標   在原來的<select ng-options="">標簽上新加一個屬性 select-search 就能支持查找的功能。如果這個屬性沒起作用,也不影響原來的select的功能。
   問題

1.在selectSearch指令里,怎么獲取到ng-options里的數據源,以及指定的value(option標簽的value)和text(option標簽里的text)字段名。

2.用什么方式來篩選?是每次顯示匹配項,隱藏不匹配項還是毎次從數據源里匹配,重新生成結點。

   思路

1.參考angular自帶指令ng-options來獲取數據源和value,text字段名。特別說明,僅支持ng-options="obj.value as obj.text for obj in list"的普通形式,那些帶分組的等等,暫不支持哈。 

2.重新生成結點。(為什么這么選擇,方便呀!)

 

 

 

 

 

 

 二.具體實現

 


 

1.代碼部分

1.1 js代碼(請引先引入jquery,不然會報錯)

  1   /**
  2    * 帶篩選功能的下拉框
  3    * 使用方法 <select ngc-select-search name="select1" ng-options="">
  4    * 說明[ select 一定要有name,ng-options 屬性]
  5    */
  6   .directive('ngcSelectSearch', function($animate, $compile, $parse) {
  7 
  8       function parseOptions(optionsExp, element, scope) {
  9           // ngOptions里的正則
 10           var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
 11 
 12           var match = optionsExp.match(NG_OPTIONS_REGEXP);
 13           if (!(match)) {
 14               console.log('ng-options 表達式有誤')
 15           }
 16           var valueName = match[5] || match[7];
 17           var keyName = match[6];
 18           var displayFn = $parse(match[2]);
 19           var keyFn = $parse(match[1]);
 20           var valuesFn = $parse(match[8]);
 21 
 22           var labelArray = [],
 23               idArray = [],
 24               optionValues = [];
 25           scope.$watch(match[8], function(newValue, oldValue) {
 26               if (newValue && newValue.length > 0) {
 27                   optionValues = valuesFn(scope) || [];
 28                   labelArray = [];
 29                   idArray = []
 30                   for (var index = 0, l = optionValues.length; index < l; index++) {
 31                       var it = optionValues[index];
 32                       if (match[2] && match[1]) {
 33                           var localIt = {};
 34                           localIt[valueName] = it;
 35                           var label = displayFn(scope, localIt);
 36                           var dataId = keyFn(scope, localIt);
 37                           labelArray.push(label);
 38                           idArray.push(dataId);
 39                       }
 40                   }
 41 
 42                   scope.options = {
 43                       'optionValues': optionValues,
 44                       'labelArray': labelArray,
 45                       'idArray': idArray
 46                   }
 47               }
 48           });
 49       }
 50       return {
 51           restrict: 'A',
 52           require: ['ngModel'],
 53           priority: 100,
 54           replace: false,
 55           scope: true,
 56           template: '<div class="chose-container">' +
 57               '<div class="chose-single"><span class="j-view"></span><i class="glyphicon glyphicon-remove"></i></div>' +
 58               '<div class="chose-drop chose-hide j-drop">' +
 59               '<div class="chose-search">' +
 60               '<input class="j-key" type="text" autocomplete="off">' +
 61               '</div>' +
 62               '<ul class="chose-result">' +
 63               // '<li ng-repeat="'+repeatTempl+'" data-id="'+keyTempl+'" >{{'+ valueTempl+'}}</li>'+
 64               '</ul>' +
 65               '</div>' +
 66               '</div>',
 67           link: {
 68               pre: function selectSearchPreLink(scope, element, attr, ctrls) {
 69 
 70                   var tmplNode = $(this.template).first();
 71 
 72                   var modelName = attr.ngModel,
 73                       name = attr.name? attr.name:('def'+Date.now());
 74                   tmplNode.attr('id', name + '_chosecontianer');
 75 
 76                   $animate.enter(tmplNode, element.parent(), element);
 77               },
 78               post: function selectSearchPostLink(scope, element, attr, ctrls) {
 79                   var choseNode = element.next(); //$('#'+attr.name +'_chosecontianer');
 80                   choseNode.addClass(attr.class);
 81                   element.addClass('chose-hide');
 82                   // 當前選中項
 83                   var ngModelCtrl = ctrls[0];
 84                   if (!ngModelCtrl || !attr.name) return;
 85 
 86                   parseOptions(attr.ngOptions, element, scope);
 87                   var rs = {};
 88 
 89                   function setView() {
 90                       var currentKey = ngModelCtrl.$modelValue;
 91                       if (isNaN(currentKey) || !currentKey) {
 92                           currentKey = '';
 93                           choseNode.find('.j-view:first').text('請選擇');
 94                           choseNode.find('i').addClass('chose-hide');
 95                       }
 96                       if ((currentKey + '').length > 0) {
 97                           for (var i = 0, l = rs.idArray.length; i < l; i++) {
 98                               if (rs.idArray[i] == currentKey) {
 99                                   choseNode.find('.j-view:first').text(rs.labelArray[i]);
100                                   choseNode.find('i').removeClass('chose-hide');
101                                   break;
102                               }
103                           }
104                       }
105                   }
106 
107                   function setViewAndData() {
108                       if (!scope.options) {
109                           return;
110                       }
111                       rs = scope.options;
112                       setView();
113                   }
114                   scope.$watchCollection('options', setViewAndData);
115                   scope.$watch(attr.ngModel, setView);
116 
117 
118                   function getListNodes(value) {
119                       var nodes = [];
120                       value = $.trim(value);
121                       for (var i = 0, l = rs.labelArray.length; i < l; i++) {
122                           if (rs.labelArray[i].indexOf(value) > -1) {
123                               nodes.push($('<li>').data('id', rs.idArray[i]).text(rs.labelArray[i]))
124                           }
125                       }
126                       return nodes;
127 
128                   }
129                   choseNode.on('keyup', '.j-key', function() {
130                       // 搜索輸入框keyup,重新篩選列表
131                       var value = $(this).val();
132                       choseNode.find('ul:first').empty().append(getListNodes(value));
133                       return false;
134                   }).on('click', function() {
135                       choseNode.find('.j-drop').removeClass('chose-hide');
136                       if (choseNode.find('.j-view:first').text() != '請選擇') {
137                           choseNode.find('i').removeClass('chose-hide');
138                       }
139                       choseNode.find('ul:first').empty().append(getListNodes(choseNode.find('.j-key').val()));
140                       return false;
141                   }).on('click', 'ul>li', function() {
142                       var _this = $(this);
143                       ngModelCtrl.$setViewValue(_this.data('id'));
144                       ngModelCtrl.$render();
145                       choseNode.find('.j-drop').addClass('chose-hide');
146                       return false;
147 
148                   }).on('click', 'i', function() {
149                       ngModelCtrl.$setViewValue('');
150                       ngModelCtrl.$render();
151                       choseNode.find('.j-view:first').text('請選擇');
152                       return false;
153 
154                   });
155                   $(document).on("click", function() {
156                       $('.j-drop').addClass('chose-hide');
157                       choseNode.find('i').addClass('chose-hide');
158                       return false;
159                   });
160 
161               }
162           }
163       };
164   })

 

1.2 css代碼(用less寫的,以下是編譯后的)

 1 .chose-hide {
 2   position: absolute!important;
 3   top: -999em !important;
 4 }
 5 .chose-container {
 6   border: none!important;
 7   float: left;
 8   margin-right: 40px;
 9   padding: 0!important;
10   position: relative;
11 }
12 .chose-container .chose-single {
13   padding: 6px 12px;
14   color: #333;
15   width: 100%;
16   border: 1px solid #eee;
17   display: inline-block;
18   height: 30px;
19 }
20 .chose-container .chose-single::after {
21   content: '';
22   position: absolute;
23   border-width: 6px 3px;
24   border-style: solid;
25   /* border-top-color: transparent; */
26   border-left-color: transparent;
27   border-right-color: transparent;
28   border-bottom-color: transparent;
29   right: 8px;
30   top: 12px;
31 }
32 .chose-container .chose-single i {
33   width: 12px;
34   float: right;
35   right: 8px;
36   font-size: 12px;
37   height: 12px;
38   background-color: #eee;
39 }
40 .chose-container .chose-drop {
41   width: 195px;
42   position: absolute;
43   border: 1px solid #eee;
44   z-index: 1000;
45   background-color: #fff;
46 }
47 .chose-container .chose-search input[type='text'] {
48   margin: 0;
49   padding-left: 12px;
50   width: 100%;
51   height: 30px;
52   border: 1px solid #ccc;
53   float: none;
54 }
55 .chose-container .chose-result {
56   max-height: 370px;
57   overflow-y: scroll;
58   overflow-x: hidden;
59 }
60 .chose-container .chose-result li {
61   padding: 5px 12px;
62   list-style-type: none;
63 }
64 .chose-container .chose-result li:hover {
65   background-color: #e1e2e7;
66 }

 

1.3 使用及效果

<select ngc-select-search class="common-select" ng-model="aa.b" ng-options="obj.countryId as obj.countryCnName for obj in vm.countries" name="country">
<option value="">請選擇</option></select>

2.詳細說明

  程序中的關鍵點是parseOptions函數,即前面分析里的問題1。parseOptions是參考ng-options的源碼實現的,原來是想返回一個對象,這個對象里包含了數據源,但是在調試時,發現post函數中該函數返回對象里的數據為空,watch不到,所以改為用scope.options來存數據。

 

  另:碼字不易,轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。