Angular中ui-select的使用
最近工作一直很忙,沒有時間整理知識,前幾天項目中需要用到angular-ui-select,實作下拉框快速過濾效果,今天有時間研究了一下,終于搞明白了。
一、準備工作
1.安裝依賴包
(1)Angular --- V1.4.9
(2)Angular-sanitize --- V1.2.28
(3)Angular-ui-select --- V0.12.1
(4)Bootstrap --- V3.3.6
如果有需要再引入jQuery
注意: Angular-sanitize所依賴的Angular最低版本,Angular-ui-select所依賴的Angular和Angular-sanitize最低版本,隻有依賴的版本符合要求,才能實作功能,否則會報錯。
如果項目中用到的Angular版本比較低時,請安裝低版本的Angular-sanitize和Angular-ui-select,這樣,避免低版本不支援的情況。
2.安裝方法:
使用npm進行安裝
npm install [email protected] --save -dev
@+版本号表示安裝指定版本的封包件,如果不加版本号,預設安裝最新的版本。
如:npm install Angular-sanitize --save -dev
如果對npm不了解的話,可以參考:https://www.cnblogs.com/le220/p/8670349.html
二、使用方法
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。