angularjs select下拉搜索框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AngularJs下拉搜索框</title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular.min.js"></script>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <style>
        input,select{
            width: 120px;
        }
    </style>
</head>
<body>
<div ng-app="app" ng-controller="indexCtrl">
    <input type="text" ng-change="searchTextValueChange(searchTextValue)" ng-model="searchTextValue"  ng-click="searchTextInputClick()">
    <div ng-show="showSelect">
        <select ng-model="selectValues" multiple>
            <option ng-repeat="data in selectData" ng-click="selectOptionClick(data)">{{data}}</option>
        </select>
    </div>
</div>
<script>
    var app = angular.module("app",[]);
    app.controller("indexCtrl", function ($scope) {
        $scope.selectData = ["王小明","李晓红","长着长着","你是狗么","别问,问就幸福","今天又被幸福了","快乐快乐","蛇皮狗"];
        //下拉框中的数值拷贝一份
        $scope.copySelectData = $scope.selectData;
        //是否显示下拉框
        $scope.showSelect = false;
        //文本框值
        $scope.searchTextValue = "";
        $scope.selectValues = [];

        /**
         * 将下拉选的数据值赋值给文本框,并且隐藏下拉框
         */
        $scope.selectOptionClick = function (selectValue) {
            //因为加了多选属性防止多选点击置空数组再加数据 //不加multiple多选属性不现实下拉范围
            $scope.selectValues = [];
            $scope.selectValues.push(selectValue);
            $scope.showSelect = false;  //下拉框隐藏
            $scope.searchTextValue = $scope.selectValues[0];   //文本框中的值

        };
        /**
         * 获取的数据值与下拉选逐个比较,如果包含则放在临时变量副本,并用临时变量副本替换下拉选原先的数值,如果数据为空或找不到,就用初始下拉选项副本替换
         */
        $scope.searchTextValueChange = function (searchTextValue) {
            if(searchTextValue === "" || searchTextValue === undefined){
                $scope.selectData = $scope.copySelectData;
                return;
            }
            //正则匹配,不是中文不筛选数据
            if(new RegExp("[^\\u4E00-\\u9FA5]+").test(searchTextValue)){
                return;
            }
            var newData = [];  //创建一个临时下拉框副本
            angular.forEach($scope.selectData, function (data) {
                if (data.indexOf(searchTextValue)>=0){
                    newData.push(data);
                }
            });
            $scope.selectData = newData; //newData中的数值赋值给$scope.selectData
        };
        /**
         * 搜索输入框点击事件
         */
        $scope.searchTextInputClick = function () {
            if($scope.selectData.length>1){
                $scope.showSelect = true;
            }
        };
    })
</script>
</body>
</html>

 

posted @ 2019-01-29 13:29  我不会游泳  阅读(3650)  评论(0编辑  收藏  举报