Skip to content

Instantly share code, notes, and snippets.

@xudejian
Created January 10, 2014 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xudejian/8348287 to your computer and use it in GitHub Desktop.
Save xudejian/8348287 to your computer and use it in GitHub Desktop.
select2 自定义搜索提示
.ac .ac-type{
float:left;
width:50px;
clear:left;
}
.ac .select2-result-sub{
float:left;
width:225px;
}
<div>
<input type="hidden" ui-select2="inputOptions" ng-model="select3"></input>
</div>
'use strict';
angular.module('select2App')
.controller('MainCtrl', function ($scope) {
function formatData(results) {
function to_name(type) {
var types = { 0: '', 1: '洲', 2: '国家', 3: '省', 4: '城市' };
return types[type] || types[0];
}
function by_type(type) {
return {
name: to_name(type),
children: []
}
}
var nres = {};
for (var i=0, c=results.length; i<c; i++) {
var r = results[i];
nres[r.type] = nres[r.type] || by_type(r.type);
var s = nres[r.type];
s.children.push(r);
}
return $.map(nres, function(value) { return value; });
}
$scope.inputOptions = {
dropdownCssClass: 'ac',
multiple: true,
width: '300px',
escapeMarkup: function (m) { return m; },
ajax: {
url: "ac.json",
dataType: 'json',
data: function (term, page) {
return {
ver: 2,
q: term
};
},
results: function (data, page) {
return {results: formatData(data)};
}
},
initSelection: function(element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("ac.json", {
data: {
ver: 2,
q: id
},
dataType: "json"
}).done(function(data) { callback(formatData(data)); });
}
},
formatResult: function(object, container) {
if (object.children) {
container.addClass('ac-type');
return object.name;
}
return object.name;
// you can do what you want like this
var markup = "<div class='ac-result'>";
markup += "<div class='ac-left'>" + to_name(object.type) + "</div>";
markup += "<div class='ac-info'>" + object.name + "</div>";
markup += "</div>"
return markup;
},
formatSelection: function(object) {
return object.name;
},
sortResults: function(results, container) {
results.sort(function(a, b) {
return a.type - b.type;
});
return results;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment