Last active
August 29, 2015 14:16
-
-
Save dlukez/76ea5f42507ba2d810e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Null-option directive for angular-ui/ui-select. | |
* | |
* Author: Daniel Zimmermann (Github: dlukez) | |
* Version: 0.1 | |
* License: MIT | |
* URL: https://gist.github.com/dlukez/76ea5f42507ba2d810e5 | |
* Usage/demo: http://plnkr.co/edit/hogYX0loQTb57Pw6RKe7 | |
*/ | |
angular.module('dz.ui-select.null-option', []).directive('nullOption', function () { | |
var directive = { | |
restrict: 'A', | |
require: ['^uiSelect', '^ngModel'], | |
link: { | |
pre: function ($scope, $element, $attrs, controllers) { | |
// treat undefined and null as the same? | |
var isNull = angular.isDefined($attrs.looseNull) ? | |
function (value) { return value == null; } : | |
function (value) { return value === null; }; | |
// get the controllers | |
var $select = controllers[0]; | |
var ngModel = controllers[1]; | |
// get the null option | |
var nullOption = $scope.$eval($attrs[directive.name]); | |
// we are going to turn the items property on the $select | |
// controller into a getter/setter, in order to add the | |
// null option if it isn't already present in the source | |
// items list | |
var items; | |
Object.defineProperty($select, 'items', { | |
get: function () { | |
return items; | |
}, | |
set: function (value) { | |
if (value.indexOf(nullOption) === -1) { | |
value.unshift(nullOption); | |
} | |
items = value; | |
} | |
}); | |
// add a parser to convert the null option | |
// into an actual null value when it is selected | |
// (this should run after $select's parser) | |
ngModel.$parsers.push(function (value) { | |
return value === nullOption ? null : value; | |
}); | |
// add a formatter to convert a null value | |
// into the null option when the model is set | |
// (this should run before $select's formatter) | |
ngModel.$formatters.unshift(function (value) { | |
return isNull(value) ? nullOption : value; | |
}); | |
} | |
} | |
}; | |
return directive; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment