Angular中ui-select的使用

Angular中ui-select的使用

最近工做一直很忙,沒有時間整理知識,前幾天項目中須要用到angular-ui-select,實現下拉框快速過濾效果,今天有時間研究了一下,終於搞明白了。html

1、準備工做

1.安裝依賴包

(1)Angular  ---   V1.4.9git

(2)Angular-sanitize  ---  V1.2.28github

(3)Angular-ui-select  ---  V0.12.1npm

(4)Bootstrap  ---  V3.3.6bootstrap

若是有須要再引入jQueryapp

注意: Angular-sanitize所依賴的Angular最低版本,Angular-ui-select所依賴的Angular和Angular-sanitize最低版本,只有依賴的版本符合要求,才能實現功能,不然會報錯。ui

若是項目中用到的Angular版本比較低時,請安裝低版本的Angular-sanitize和Angular-ui-select,這樣,避免低版本不支持的狀況。spa

2.安裝方法:

使用npm進行安裝3d

npm install Angular-sanitize@1.2.28 --save -devcode

@+版本號表示安裝指定版本的包文件,若是不加版本號,默認安裝最新的版本。

如:npm install Angular-sanitize --save -dev

若是對npm不瞭解的話,能夠參考:https://www.cnblogs.com/le220/p/8670349.html

2、使用方法

1.首先依次引入所須要的文件

 

注意引入的前後順序

2.html代碼

 1 <ui-select ng-model="$parent.test" theme="bootstrap" style="min-width: 300px;" name="oldTest" ng-change="testChange()">
 2 
 3             <ui-select-match placeholder="請選擇用戶名">{{$select.selected.name}}</ui-select-match>
 4 
 5             <ui-select-choices repeat="s in testArr| propsFilter: {name: $select.search, id: $select.search}">
 6 
 7                <div ng-bind-html="s.name | highlight: $select.search"></div>
 8 
 9             </ui-select-choices>
10 
11          </ui-select>

ui-select-match  匹配所輸或所選項在文本框展現

ui-select-choices  下拉列表的展現

ng-bind-html  綁定用戶所選擇的項,以高亮狀態展現

3.js代碼(demo2.js)

 1 /**  2  * Created by Administrator on 2018/6/22.  3  */
 4 'use strict';  5 
 6 var app = angular.module('demo', ['ngSanitize', 'ui.select']);  7 
 8 app.filter('propsFilter', function() {  9     return function(items, props) { 10         var out = []; 11 
12         if (angular.isArray(items)) { 13             var keys = Object.keys(props); 14 
15             items.forEach(function(item) { 16                 var itemMatches = false; 17 
18                 for (var i = 0; i < keys.length; i++) { 19                     var prop = keys[i]; 20                     var text = props[prop].toLowerCase(); 21                     if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { 22                         itemMatches = true; 23                         break; 24  } 25  } 26 
27                 if (itemMatches) { 28  out.push(item); 29  } 30  }); 31         } else { 32             out = items; 33  } 34 
35         return out; 36  }; 37 }); 38 
39 app.controller('DemoCtrl', ['$scope',function($scope){ 40     $scope.test = {}; 41     $scope.testArr = [ 42  { 43             id: 1, 44             name: "樂樂"
45  }, 46  { 47             id: 2, 48             name: "博博"
49  }, 50  { 51             id: 3, 52             name: "淘淘"
53  } 54  ]; 55     
56 
57     $scope.testChange = function () { 58  console.log($scope.testSelect); 59      
60  } 61 } 62 ]);

4.實現效果

    

 

固然ui-select不止這一種用法,還有許多意想不到的功能。本實例和其餘功能實如今github:https://github.com/lela520/angular-ui-select。

相關文章
相關標籤/搜索