你可以参考这个:
HTML
<div ng-controller="MyCtrl">
<input ng-change="showDialog(tagsSelections)" type="text" ui-select2="tagAllOptions" ng-model="tagsSelections" style="width:300px;" />
<pre> tagsSelection: {{tagsSelections | json}}</pre>
</div>
JS
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope, $timeout) {
// Initialize with Objects.
$scope.tagsSelection = [{
"id": "01",
"text": "Perl"
}, {
"id": "03",
"text": "JavaScript"
}];
$scope.showDialog = function (item) {
console.log(item); // if you want you can put your some logic.
};
$timeout(function () {
$scope.tagsSelection.push({
'id': '02',
'text': 'Java'
});
}, 3000);
$scope.tagData = [{
"id": "01",
"text": "Perl"
}, {
"id": "02",
"text": "Java"
}, {
"id": "03",
"text": "JavaScript"
}, {
"id": "04",
"text": "Scala"
}];
// to show some add item in good format
$scope.formatResult = function (data) {
var markup;
if (data.n === "new") markup = "<div> <button class='btn-success btn-margin'><i class='icon-plus icon-white'></i> Create :" + data.text + "</button></div>";
else markup = "<div>" + data.text + "</div>";
return markup;
};
$scope.formatSelection = function (data) {
return "<b>" + data.text + "</b></div>";
};
$scope.tagAllOptions = {
multiple: true,
data: $scope.tagData,
tokenSeparators: [","],
createSearchChoice: function (term, data) { // this will create extra tags.
if ($(data).filter(function () {
return this.v.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term,
n: "new",
s: ""
};
}
},
// initSelection: function(element, callback) { //if you want to set existing tags into select2
// callback($(element).data('$ngModelController').$modelValue);
// },
formatResult: $scope.formatResult,
formatSelection: $scope.formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) {
return m;
}
};
};
工作小提琴:快速添加新标签