angularjs - select2 - tagging with objects
http://angularjs.org/
by maxisam
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/base/jquery-ui.css">
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
<link href="http://ivaynberg.github.com/select2/select2-3.2/select2.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="https://raw.github.com/twitter/bootstrap/master/docs/assets/js/bootstrap.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script src="https://raw.github.com/angular-ui/angular-ui/master/build/angular-ui.js"></script>
<script src="http://ivaynberg.github.com/select2/select2-3.2/select2.js"></script>
<div style="border: 1px solid red;margin-bottom:10px;">angular-ui
<div ng-controller="MyCtrl">
<input type="text" id="tagsSelection" ui-select2="tagAllOptions" ng-model="tagsSelection" style="width:300px;" />
<pre>
tagsSelection: {{tagsSelection | json}}
</pre>
<button ng-click="updateVal()">Update Value</button>
<button ng-click="updateVal2()">Update Value 2</button>
<p>Value is: {{selected2}}</p>
<select ui-select2 ng-model="selected2" style="width:300px;">
<option ng-repeat="item in tagData2" selected value="{{item}}">{{item.text}}</option>
</select>
</div>
</div>
JavaScript
var myApp = angular.module('myApp', ['ui']);
// "class" for customizing select2 (with possibility to create selection items on the fly
function Select2Tagging(items,formatProperty) {
if(!formatProperty) {
formatProperty="text";
}
console.log("Select2Tagging init");
var f={};
f.formatProperty=formatProperty;
f.data=items;
var itemMap={};
$.each(items,function(index,value){
itemMap[value.id]=value;
});
f.initSelection = function(element, callback) {
var data = [];
var eleVal=element.val();
console.log("initSelection "+eleVal);
var ids = eleVal.split(",");
$(ids).each(function() {
var id=this;
$(f.data).each(function() {
if (id.localeCompare(""+this.id)==0) data.push(this);
});
});
callback(data);
};
f.createSearchChoice = function(term, data) {
console.log("createSearchChoice "+term +" data "+data);
if ($(data).filter(function() {
return this[f.formatProperty].localeCompare(term) === 0;
//return this.text.localeCompare(term) === 0;
}
).length === 0) {
var result= {
id: term,
//text: term
};
result[f.formatProperty]=term;
return result;
}
};
formatResult=function(item) {
console.log("formatResult "+item);
if(item[f.formatProperty]) {
return item[f.formatProperty];
} else {
return item;
}
};
formatSelection=function(item) {
if(item[f.formatProperty]) {
return item[f.formatProperty];
} else {
return item;
}
};
f.formatResult= formatResult;
f.formatSelection= formatSelection;
f.multiple=true;
return f;
}
function...