Angularjs implements select drop-down box sample code with search and filter function

高洛峰
Release: 2016-12-29 10:29:16
Original
1351 people have browsed it

前言

对于select的下拉列表,像国家选择这样的功能,全世界那么多国家,一直拉滚动条多辛苦,眼睛也要盯着找,累!所以为优化用户体验,带查找功能的下拉框是非常非常有必要的。都知道jquery里有这样的插件,但我们用的是Angularjs,更希望用双向绑定,指令的方式优雅地解决这个问题。

分析

我们的目标是在原来的 * 说明[ 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 表达式有误') } 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: '

' + '
' + '
' + '' + '
    ' + // '
  • {{'+ valueTempl+'}}
  • '+ '
' + '
' + '
', 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'); // 当前选中项 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('请选择'); 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($('
  • ').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() != '请选择') { 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('请选择'); return false; }); $(document).on("click", function() { $('.j-drop').addClass('chose-hide'); choseNode.find('i').addClass('chose-hide'); return false; }); } } }; })Copy after login1.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; }Copy after login使用及效果Copy after login详细说明程序中的关键点是parseOptions函数,即前面分析里的问题1。parseOptions是参考ng-options的源码实现的,原来是想返回一个对象,这个对象里包含了数据源,但是在调试时,发现post函数中该函数返回对象里的数据为空,watch不到,所以改为用scope.options来存数据。总结以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。更多Angularjs实现带查找筛选功能的select下拉框示例代码相关文章请关注PHP中文网!Related labels:angularjs 下拉框 筛选source:php.cnPrevious article:Detailed explanation of function throttling that triggers the onScroll event in JavaScriptNext article:AngularJS uses the ng-repeat directive to implement drop-down boxesStatement of this WebsiteThe content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cnLatest Articles by AuthorExamples of html settings for bold, italic, underline, strikethrough and other font effects1970-01-01 08:00:00Implement a Java version of Redis1970-01-01 08:00:00The simplest WeChat applet Demo1970-01-01 08:00:00Introduction to simple operation methods of pandas.DataFrame (create, index, add and delete) in python1970-01-01 08:00:00WeChat Mini Program: Example of how to implement tabs effect1970-01-01 08:00:00Python constructs custom methods to beautify dictionary structure output1970-01-01 08:00:00HTML5: Use Canvas to process Video in real time1970-01-01 08:00:00Asp.net uses SignalR to send pictures1970-01-01 08:00:00WeChat Mini Program Development Tutorial-App() and Page() Function Overview1970-01-01 08:00:00Detailed explanation of how to use python redis1970-01-01 08:00:00Latest IssuesWhy is the selected drop-down box value not displayed?I'm building a function for my WordPress plugin that displays a dropdown list of all avail...From 2023-09-12 13:22:2601340Method to clear selected value of ComboBox in HeadlessUII'm trying to clear the selected option every time the user opens the dropdown box. Curren...From 2023-09-09 20:20:3601205Why can't I get the entered value from $_POST?Preface: I'm relatively new to PHP and HTML, so I apologize in advance if there are any ob...From 2023-09-06 17:12:2301304Vue.js disable/enable dropdown menu if checkbox is checked?I'm trying to enable/disable dropdown:combination selection when my box is checked. When I...From 2023-08-29 23:14:0701310The title of Unable to scroll to top of flex item in overflow container is rewritten as: Unable to scroll to top of flex item in overflow containerWhile trying to create a useful modal using flexbox, I came across what appears to be a br...From 2023-08-22 14:58:0602199Related TopicsMore>Why webstorm cannot run the filebinary arithmeticHow to increase fans of Douyin quickly and effectivelyHow to modify the hosts fileHow long does it take for Douyin recharge to arrive?What is the reason for DNS resolution failure?Solutions to unknown software exception exceptions in computer applicationsWhy can't I delete the last blank page in word?Popular Recommendationswhat does js meanHow to convert string to array in js?How to refresh the page using javascriptHow to delete an item in js arrayHow to use sqrt functionPopular TutorialsMore>Related TutorialsPopular RecommendationsLatest coursesThe latest ThinkPHP 5.1 world premiere video tutorial (60 days to become a PHP expert online training course)1394913PHP introductory tutorial one: Learn PHP in one week4206629JAVA Beginner's Video Tutorial2350921Little Turtle's zero-based introduction to learning Python video tutorial493319PHP zero-based introductory tutorial826317The latest ThinkPHP 5.1 world premiere video tutorial (60 days to become a PHP expert online training course)1394913 times of learningJAVA Beginner's Video Tutorial2350921 times of learningLittle Turtle's zero-based introduction to learning Python video tutorial493319 times of learningQuick introduction to web front-end development213417 times of learningMaster PS video tutorials from scratch843264 times of learning[Web front-end] Node.js quick start3149 times of learningComplete collection of foreign web development full-stack courses2544 times of learningGo language practical GraphQL1989 times of learning550W fan master learns JavaScript from scratch step by step465 times of learningPython master Mosh, a beginner with zero basic knowledge can get started in 6 hours10893 times of learningLatest DownloadsMore>Web EffectsWebsite Source CodeWebsite MaterialsFront End Template[form button] jQuery enterprise message form contact code[Player special effects] HTML5 MP3 music box playback effects[Menu navigation] HTML5 cool particle animation navigation menu special effects[form button] jQuery visual form drag and drop editing code[Player special effects] VUE.JS imitation Kugou music player code[html5 special effects] Classic html5 pushing box game[Picture special effects] jQuery scrolling to add or reduce image effects[Photo album effects] CSS3 personal album cover hover zoom effect[Front-end template] Home Decor Cleaning and Repair Service Company Website Template[Front-end template] Fresh color personal resume guide page template[Front-end template] Designer Creative Job Resume Web Template[Front-end template] Modern engineering construction company website template[Front-end template] Responsive HTML5 template for educational service institutions[Front-end template] Online e-book store mall website template[Front-end template] IT technology solves Internet company website template[Front-end template] Purple style foreign exchange trading service website template[PNG material] Cute summer elements vector material (EPS PNG)[PNG material] Four red 2023 graduation badges vector material (AI EPS PNG)[banner picture] Singing bird and cart filled with flowers design spring banner vector material (AI EPS)[PNG material] Golden graduation cap vector material (EPS PNG)[PNG material] Black and white style mountain icon vector material (EPS PNG)[PNG material] Superhero silhouette vector material (EPS PNG) with different color cloaks and different poses[banner picture] Flat style Arbor Day banner vector material (AI+EPS)[PNG material] Nine comic-style exploding chat bubbles vector material (EPS+PNG)[Front-end template] Home Decor Cleaning and Repair Service Company Website Template[Front-end template] Fresh color personal resume guide page template[Front-end template] Designer Creative Job Resume Web Template[Front-end template] Modern engineering construction company website template[Front-end template] Responsive HTML5 template for educational service institutions[Front-end template] Online e-book store mall website template[Front-end template] IT technology solves Internet company website template[Front-end template] Purple style foreign exchange trading service website templateAbout usDisclaimerSitemapphp.cn:Public welfare online PHP training,Help PHP learners grow quickly!