对于那些为 bootstrap-tagsinput 寻找一个简单指令实现的人,我已经实现了非常简单的指令:
'use strict';
angular.module('yourApp')
.directive('tagsInputEditor', function () {
return {
restrict: 'E',
scope: {
options: '@', //receive all the options in a JSON array - one-way binding
selection: '='//two-way binding - the selected tags to use
},
replace: true,
template: '<input id="inputCategories" type="text" data-role="tagsinput"/>',
link: function (scope, element, attrs) {
var el = $(element);
var options = JSON.parse(scope.options);
//select initial values for typeahead:
el.val(function () {
return cat.allCategories.map(function (category) {
return category.Tag;//the object used has a Tag property
});
});
//configuration of typeahead options
el.tagsinput({
typeahead: {
source: options.map(function (option) {
return option.Tag;
})
},
freeInput: true
});
//event handlers to sync data
el.on('itemAdded', syncItems);
el.on('itemRemoved', syncItems);
function syncItems() {
var items = el.val().split(',');
//clear all items and store the new items selection
scope.selection.length = 0;
for (var i = 0; i < items.length; i++) {
scope.selection.push(items[i]);
}
//you should tell angular to refresh the scope and send data back to the scope
scope.$apply();
}
}
};
});
用法是这样的:
<tags-input-editor options="{{model.categories}}" selection="model.selectedCategories" />
您会看到,控制器使用类别和选定类别定义模型。这对我来说已经足够了。我没有使用组件的其他功能,但从这里开始很容易继续 - 我在指令中使用传统的 jQuery 代码,组件的文档似乎就足够了。