Angularjs實(shí)現(xiàn)帶查找篩選功能的select下拉框示例代碼
前言
對(duì)于select的下拉列表,像國(guó)家選擇這樣的功能,全世界那么多國(guó)家,一直拉滾動(dòng)條多辛苦,眼睛也要盯著找,累!所以為優(yōu)化用戶體驗(yàn),帶查找功能的下拉框是非常非常有必要的。都知道jquery里有這樣的插件,但我們用的是Angularjs,更希望用雙向綁定,指令的方式優(yōu)雅地解決這個(gè)問(wèn)題。
分析
我們的目標(biāo)是在原來(lái)的<select ng-options="">
標(biāo)簽上新加一個(gè)屬性 select-search
就能支持查找的功能。如果這個(gè)屬性沒(méi)起作用,也不影響原來(lái)的select的功能。
問(wèn)題
1.在selectSearch
指令里,怎么獲取到ng-options
里的數(shù)據(jù)源,以及指定的value(option標(biāo)簽的value)和text(option標(biāo)簽里的text)字段名。
2.用什么方式來(lái)篩選?是每次顯示匹配項(xiàng),隱藏不匹配項(xiàng)還是毎次從數(shù)據(jù)源里匹配,重新生成結(jié)點(diǎn)。
解決思路
1.參考angular自帶指令ng-options
來(lái)獲取數(shù)據(jù)源和value
,text
字段名。特別說(shuō)明,僅支持ng-options="obj.value as obj.text for obj in list"
的普通形式,那些帶分組的等等,暫不支持哈。
2.重新生成結(jié)點(diǎn)。(為什么這么選擇,方便呀?。?/p>
具體實(shí)現(xiàn)
1.代碼部分
1.1 js代碼(請(qǐng)引先引入jquery,不然會(huì)報(bào)錯(cuò))
/** * 帶篩選功能的下拉框 * 使用方法 <select ngc-select-search name="select1" ng-options=""> * 說(shuō)明[ select 一定要有name,ng-options 屬性] */ .directive('ngcSelectSearch', function($animate, $compile, $parse) { function parseOptions(optionsExp, element, scope) { // ngOptions里的正則 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]+?))?$/; var match = optionsExp.match(NG_OPTIONS_REGEXP); if (!(match)) { console.log('ng-options 表達(dá)式有誤') } var valueName = match[5] || match[7]; var keyName = match[6]; var displayFn = $parse(match[2]); var keyFn = $parse(match[1]); var valuesFn = $parse(match[8]); var labelArray = [], idArray = [], optionValues = []; scope.$watch(match[8], function(newValue, oldValue) { if (newValue && newValue.length > 0) { optionValues = valuesFn(scope) || []; labelArray = []; idArray = [] for (var index = 0, l = optionValues.length; index < l; index++) { var it = optionValues[index]; if (match[2] && match[1]) { var localIt = {}; localIt[valueName] = it; var label = displayFn(scope, localIt); var dataId = keyFn(scope, localIt); labelArray.push(label); idArray.push(dataId); } } scope.options = { 'optionValues': optionValues, 'labelArray': labelArray, 'idArray': idArray } } }); } return { restrict: 'A', require: ['ngModel'], priority: 100, replace: false, scope: true, template: '<div class="chose-container">' + '<div class="chose-single"><span class="j-view"></span><i class="glyphicon glyphicon-remove"></i></div>' + '<div class="chose-drop chose-hide j-drop">' + '<div class="chose-search">' + '<input class="j-key" type="text" autocomplete="off">' + '</div>' + '<ul class="chose-result">' + // '<li ng-repeat="'+repeatTempl+'" data-id="'+keyTempl+'" >{{'+ valueTempl+'}}</li>'+ '</ul>' + '</div>' + '</div>', link: { pre: function selectSearchPreLink(scope, element, attr, ctrls) { var tmplNode = $(this.template).first(); var modelName = attr.ngModel, name = attr.name? attr.name:('def'+Date.now()); tmplNode.attr('id', name + '_chosecontianer'); $animate.enter(tmplNode, element.parent(), element); }, post: function selectSearchPostLink(scope, element, attr, ctrls) { var choseNode = element.next(); //$('#'+attr.name +'_chosecontianer'); choseNode.addClass(attr.class); element.addClass('chose-hide'); // 當(dāng)前選中項(xiàng) var ngModelCtrl = ctrls[0]; if (!ngModelCtrl || !attr.name) return; parseOptions(attr.ngOptions, element, scope); var rs = {}; function setView() { var currentKey = ngModelCtrl.$modelValue; if (isNaN(currentKey) || !currentKey) { currentKey = ''; choseNode.find('.j-view:first').text('請(qǐng)選擇'); choseNode.find('i').addClass('chose-hide'); } if ((currentKey + '').length > 0) { for (var i = 0, l = rs.idArray.length; i < l; i++) { if (rs.idArray[i] == currentKey) { choseNode.find('.j-view:first').text(rs.labelArray[i]); choseNode.find('i').removeClass('chose-hide'); break; } } } } function setViewAndData() { if (!scope.options) { return; } rs = scope.options; setView(); } scope.$watchCollection('options', setViewAndData); scope.$watch(attr.ngModel, setView); function getListNodes(value) { var nodes = []; value = $.trim(value); for (var i = 0, l = rs.labelArray.length; i < l; i++) { if (rs.labelArray[i].indexOf(value) > -1) { nodes.push($('<li>').data('id', rs.idArray[i]).text(rs.labelArray[i])) } } return nodes; } choseNode.on('keyup', '.j-key', function() { // 搜索輸入框keyup,重新篩選列表 var value = $(this).val(); choseNode.find('ul:first').empty().append(getListNodes(value)); return false; }).on('click', function() { choseNode.find('.j-drop').removeClass('chose-hide'); if (choseNode.find('.j-view:first').text() != '請(qǐng)選擇') { choseNode.find('i').removeClass('chose-hide'); } choseNode.find('ul:first').empty().append(getListNodes(choseNode.find('.j-key').val())); return false; }).on('click', 'ul>li', function() { var _this = $(this); ngModelCtrl.$setViewValue(_this.data('id')); ngModelCtrl.$render(); choseNode.find('.j-drop').addClass('chose-hide'); return false; }).on('click', 'i', function() { ngModelCtrl.$setViewValue(''); ngModelCtrl.$render(); choseNode.find('.j-view:first').text('請(qǐng)選擇'); return false; }); $(document).on("click", function() { $('.j-drop').addClass('chose-hide'); choseNode.find('i').addClass('chose-hide'); return false; }); } } }; })
1.2 css代碼(用less寫的,以下是編譯后的)
.chose-hide { position: absolute!important; top: -999em !important; } .chose-container { border: none!important; float: left; margin-right: 40px; padding: 0!important; position: relative; } .chose-container .chose-single { padding: 6px 12px; color: #333; width: 100%; border: 1px solid #eee; display: inline-block; height: 30px; } .chose-container .chose-single::after { content: ''; position: absolute; border-width: 6px 3px; border-style: solid; /* border-top-color: transparent; */ border-left-color: transparent; border-right-color: transparent; border-bottom-color: transparent; right: 8px; top: 12px; } .chose-container .chose-single i { width: 12px; float: right; right: 8px; font-size: 12px; height: 12px; background-color: #eee; } .chose-container .chose-drop { width: 195px; position: absolute; border: 1px solid #eee; z-index: 1000; background-color: #fff; } .chose-container .chose-search input[type='text'] { margin: 0; padding-left: 12px; width: 100%; height: 30px; border: 1px solid #ccc; float: none; } .chose-container .chose-result { max-height: 370px; overflow-y: scroll; overflow-x: hidden; } .chose-container .chose-result li { padding: 5px 12px; list-style-type: none; } .chose-container .chose-result li:hover { background-color: #e1e2e7; }
使用及效果
<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="">請(qǐng)選擇</option></select>
詳細(xì)說(shuō)明
程序中的關(guān)鍵點(diǎn)是parseOptions
函數(shù),即前面分析里的問(wèn)題1。parseOptions
是參考ng-options
的源碼實(shí)現(xiàn)的,原來(lái)是想返回一個(gè)對(duì)象,這個(gè)對(duì)象里包含了數(shù)據(jù)源,但是在調(diào)試時(shí),發(fā)現(xiàn)post
函數(shù)中該函數(shù)返回對(duì)象里的數(shù)據(jù)為空,watch
不到,所以改為用scope.options
來(lái)存數(shù)據(jù)。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。
- AngularJS動(dòng)態(tài)生成select下拉框的方法實(shí)例
- angularjs 動(dòng)態(tài)從后臺(tái)獲取下拉框的值方法
- angularJs-$http實(shí)現(xiàn)百度搜索時(shí)的動(dòng)態(tài)下拉框示例
- AngularJS中下拉框的高級(jí)用法示例
- AngularJS中下拉框的基本用法示例
- Angularjs實(shí)現(xiàn)下拉框聯(lián)動(dòng)的示例代碼
- angularjs下拉框空白的解決辦法
- angularjs 實(shí)現(xiàn)帶查找篩選功能的select下拉框?qū)嵗?/a>
- AngularJS使用ng-repeat指令實(shí)現(xiàn)下拉框
- AngularJS實(shí)現(xiàn)多級(jí)下拉框
相關(guān)文章
AngularJS使用ng-repeat指令實(shí)現(xiàn)下拉框
這篇文章主要介紹了AngularJS使用ng-repeat指令實(shí)現(xiàn)下拉框的相關(guān)資料,非常不錯(cuò),感興趣的朋友一起看下吧,需要的朋友可以參考下2016-08-08解決AngualrJS頁(yè)面刷新導(dǎo)致異常顯示問(wèn)題
本篇文章主要介紹了解決AngualrJS頁(yè)面刷新導(dǎo)致異常顯示問(wèn)題的方法。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-04-04Angularjs實(shí)現(xiàn)控制器之間通信方式實(shí)例總結(jié)
這篇文章主要介紹了Angularjs實(shí)現(xiàn)控制器之間通信方式,結(jié)合實(shí)例形式總結(jié)分析了AngularJS控制器常用通信方式及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2018-03-03Angular JS 生成動(dòng)態(tài)二維碼的方法
這篇文章主要介紹了Angular JS 生成動(dòng)態(tài)二維碼的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-02-02用AngularJS的指令實(shí)現(xiàn)tabs切換效果
這篇文章介紹的是寫一個(gè)通過(guò)指令嵌套實(shí)現(xiàn)tabs功能的指令模塊,這也是我在一個(gè)項(xiàng)目中應(yīng)用到的,現(xiàn)在分享給大家,有需要的可以參考借鑒。2016-08-08基于angular2 的 http服務(wù)封裝的實(shí)例代碼
這篇文章主要介紹了基于angular2 的 http服務(wù)封裝實(shí)例代碼,2017-06-06