ngtags是angular生态下一个标签组插件,功能很强大,支持自动完成(Autocomplete),使用也非常的方便。
下载地址:https://github.com/mbenford/ngTagsInput
API地址:http://mbenford.github.io/ngTagsInput/documentation/api
在线演示:http://mbenford.github.io/ngTagsInput/demos
使用方法:
一、引入ngTags资源
<link rel="stylesheet" href="js/vendor/angular/ng-tags-input/ng-tags-input.css" type="text/css" >
<link rel="stylesheet" href="js/vendor/angular/ng-tags-input/ng-tags-input.bootstrap.css" type="text/css" >
<script type="text/javascript" src="js/vendor/angular/ng-tags-input/ng-tags-input.js"></script>
二、js代码
.......
app.controller('TagsController',['$scope',function($scope){
$scope.initTags = [{text:"tag1"},{text:"中文tag"}];
$scope.srcTags = ["srcTag1","srcTag2"];
$scope.autoTags = [{text:"aTag1"},{text:"aTag2"},{text:"bTag1"},{text:"bTag2"},{text:"中文标签1"},{text:"中文标签2"}];
$scope.tagAdded = function(tag) {
console.log('Added: ' + tag.text);
};
$scope.tagRemoved = function(tag) {
if($scope.srcTags.indexOf(tag.text)<0)$scope.srcTags.push(tag.text);
console.log('Removed: ' + tag.text);
};
$scope.pushTag = function(txt){
$scope.initTags.push({text: txt});
$scope.srcTags.splice($scope.srcTags.indexOf(txt), 1);
}
$scope.loadTags = function($query) {
console.log($query);
return $scope.autoTags.filter(function(tg) {
return tg.text.toLowerCase().indexOf($query.toLowerCase()) != -1;
});
};
$scope.submitForm = function(){
alert(angular.toJson($scope.initTags));
console.log($scope.initTags);
}
}])
三、HTML代码
<script type="text/ng-template" id="auto-template">
<span ng-bind-html="$highlight($getDisplayText())"></span>
</script>
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3">标签</h1>
</div>
<div class="wrapper-md" ng-controller="TagsController">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<form name="formValidate" ng-submit="submitForm()" class="form-horizontal form-validation">
<div class="form-group">
<label class="col-sm-4 control-label">Tab/Enter键完成输入,最多3个,每个最大5字符,最小1字符:<br>
<span class="text-muted">使用max-length,min-length配置,删除或添加时都会有监听方法,通过开发者工具可查看</span>
</label>
<div class="col-sm-4">
<tags-input max-tags="3" replace-spaces-with-dashes="false" display-property="text" on-tag-added="tagAdded($tag)" on-tag-removed="tagRemoved($tag)" max-length="5" min-length="1" ng-model="initTags">
<auto-complete source="loadTags($query)"
min-length="0"
load-on-focus="true"
load-on-empty="true"
max-results-to-show="32"
template="auto-template">
</auto-complete>
</tags-input>
</div>
<div class="col-sm-4">
历史和预定义标签:<br>
<div class="label bg-primary pos-rlt m-r inline wrapper-xs" ng-click="pushTag(st)" ng-repeat="st in srcTags">
<i class="arrow right arrow-primary"></i>{{st}}
</div>
</div>
</div>
<footer class="panel-footer text-center">
<button type="submit" class="btn btn-info">提交标签</button>
</footer>
</form>
</div>
</div>
</div>
</div>
</div>