angularjs - select2 - tagging with objects

http://angularjs.org/

by johnoscott

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script src="https://raw.github.com/ivaynberg/select2/master/select2.js"></script>
<script src="http://angular-ui.github.com/angular-ui/build/angular-ui.js"></script>
<link rel="stylesheet" href="http://angular-ui.github.com/lib/select2/select2.css">
<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;" ></input>
        <pre>
            tagsSelection: {{tagsSelection | json}}
        </pre>
        <button ng-click="updateVal()">Update Value</button>
        <button ng-click="updateVal2()">Update Value 2</button>
    </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...