Angular: Empty Fiddle
http://angularjs.org/
by boneskull
HTML
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/3.4.1/select2.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.4.1/select2.css">
<div ng-controller="MyCtrl">
<select ui-select2 ng-options="item for item in items" ng-model="selectedItem"></select>
</div>
JavaScript
/**
* Enhanced Select2 Dropmenus
*
* @AJAX Mode - When in this mode, your value will be an object (or array of objects) of the data used by Select2
* This change is so that you do not have to do an additional query yourself on top of Select2's own query
* @params [options] {object} The configuration options passed to $.fn.select2(). Refer to the documentation
*/
angular.module('ui.directives', []).directive('uiSelect2', ['$timeout', '$parse', function ($timeout, $parse) {
var options = {};
return {
require: '?ngModel',
compile: function (tElm, tAttrs) {
var watch,
repeatOption,
repeatAttr,
isSelect = tElm.is('select'),
/** ADDED LINE BELOW **/
hasNoNgOptions = isSelect && !tAttrs.ngOptions,
isMultiple = (tAttrs.multiple !== undefined);
// Enable watching of the options dataset if in use
if (tElm.is('select')) {
repeatOption = tElm.find('option[ng-repeat], option[data-ng-repeat]');
if (repeatOption.length) {
repeatAttr = repeatOption.attr('ng-repeat') || repeatOption.attr('data-ng-repeat');
watch = jQuery.trim(repeatAttr.split('|')[0]).split(' ').pop();
}
}
return function (scope, elm, attrs, controller) {
// instance-specific options
var opts = angular.extend({}, options, scope.$eval(attrs.uiSelect2)), getter;
if (isSelect) {
// Use <select multiple> instead
delete opts.multiple;
delete opts.initSelection;
} else if (isMultiple) {
opts.multiple = true;
}
if (controller) {
// Watch the model for programmatic changes
controller.$render = function () {
/** MODIFIED LINE BELOW **/
if (hasNoNgOptions) {
elm.select2('val', controller.$viewValue);
} else {
if (isMultiple) {
if (!controller.$viewValue) {
...