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>

 


免責聲明!

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



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM