对于那些寻找一个简单的指令,用于引导,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代码,组件的文档似乎已经足够。