AngularJS UI Select 指南
1. 项目介绍
AngularJS UI Select 是一个基于 AngularJS 的组件,它提供了类似 Select2 和 Selectize 的功能,支持搜索、多选以及标签创建等功能。该项目不需要依赖 jQuery 或其他第三方 JavaScript 库,只需要 AngularJS 和 Angular Sanitize 作为基础依赖。UI Select 提供了多种主题样式,如 Bootstrap、Select2 和 Selectize。
2. 项目快速启动
安装依赖
确保已安装以下依赖项:
- AngularJS(要求 1.2.x 版本以上,测试兼容 1.5.3)
- Angular-Sanitize (版本需与 AngularJS 匹配)
可以通过 npm 或 bower 进行安装:
# 使用 npm
npm install angular-ui-select angular-sanitize
# 使用 bower
bower install angular-ui-select angular-sanitize
引入文件
在 HTML 文件中引入相应的 CSS 和 JS 文件:
<link href="path/to/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="path/to/bower_components/angular/angular.min.js"></script>
<script src="path/to/bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="path/to/bower_components/angular-ui-select/dist/select.min.js"></script>
<link href="path/to/bower_components/angular-ui-select/dist/select.css" rel="stylesheet"/>
添加模块依赖
在你的 AngularJS 应用模块中添加 ui.select
和 ngSanitize
依赖:
angular.module('yourApp', ['ui.select', 'ngSanitize']);
使用示例
在 HTML 中添加 UI Select 组件:
<div ng-app="yourApp" ng-controller="YourController">
<ui-select ng-model="selectedPerson">
<ui-select-match placeholder="选择人员">{{ $select.selected.name }}</ui-select-match>
<ui-select-choices repeat="person in people | filter: $select.search">
<div ng-bind="person.name"></div>
</ui-select-choices>
</ui-select>
</div>
在控制器中定义数据源:
function YourController($scope) {
$scope.people = [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 },
// 更多...
];
}
3. 应用案例和最佳实践
-
动态绑定: 当数据是异步获取时,可以使用
$timeout
或者$http
服务加载数据,然后更新模型。function YourController($scope, $timeout) { $timeout(function() { $scope.people = [ // 异步获取的数据... ]; }); }
-
禁用搜索:在不希望用户提供搜索功能时,可以设置
search-enabled=false
。<ui-select search-enabled="false" ...></ui-select>
-
自定义标签:实现用户输入的新值自动转化为标签,设置
tagging
属性。<ui-select tagging="addTag" ...></ui-select>
function YourController($scope) { $scope.addTag = function(item) { if (!item.$$hashKey) item.$$hashKey = Math.random(); $scope.people.push(item); return item; }; }
-
分组选项:通过
group-by
设置一个属性名,将选项按该属性值进行分组。<ui-select group-by="groupByFunction" ...></ui-select>
$scope.groupByFunction = function(person) { return person.department; };
4. 典型生态项目
- Bootstrap: UI Select 预设了与 Bootstrap 的集成,使用
theme="bootstrap"
可以获得 Bootstrap 样式。 - Select2: 虽然 UI Select 主要设计为替代 Bootstrap 的下拉框,但它也可以模仿 Select2 的样式,只需导入相关 CSS。
- Selectize: 同样,UI Select 支持 Selectize 主题,可以轻松地通过更改 CSS 实现。
本文简要介绍了 AngularJS UI Select 的基本使用方法,更多详细信息和高级特性,请查阅其官方 GitHub 页面:https://github.com/angular-ui/ui-select 。