Skip to content

Instantly share code, notes, and snippets.

@jens1101
Last active May 22, 2018 11:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jens1101/fcdd3d2434fdcb27be554ecc71bf7f33 to your computer and use it in GitHub Desktop.
Save jens1101/fcdd3d2434fdcb27be554ecc71bf7f33 to your computer and use it in GitHub Desktop.
An angular component wrapper for bootstrap select.
var app = angular.module('app', [])
app.component('selectPicker', {
template: '<div ng-transclude ng-show="$ctrl.show"></div>',
require: {
ngModel: '^ngModel'
},
bindings: {
options: '<',
disable: '<'
},
transclude: true,
controller: SelectCtrl
})
function SelectCtrl($element, $timeout) {
var $ctrl = this;
var selectElement;
$ctrl.show = false;
$ctrl.$onInit = function() {
$timeout(function() {
selectElement = $('select', $element);
selectElement.selectpicker($ctrl.options);
$ctrl.show = true;
selectElement.on('change', function() {
$ctrl.ngModel.$setViewValue(getElementValue());
});
$ctrl.ngModel.$render = function() {
setElementValue($ctrl.ngModel.$modelValue);
};
// I first set the element to the current model value. If the model value is valid
// then the element will change
setElementValue($ctrl.ngModel.$modelValue);
// I set the model to te current element value. If the previous step successfully
// changed the element, then this will not have any effect. Otherwise the model will
// be changed to the current value of the select.
$ctrl.ngModel.$setViewValue(getElementValue());
});
};
$ctrl.$onChanges = function(changesObj) {
if ('disable' in changesObj && !changesObj.disable.isFirstChange()) {
selectElement.prop('disabled', $ctrl.disable);
selectElement.selectpicker('refresh');
}
};
function setElementValue(value) {
selectElement.val(value);
selectElement.selectpicker('render');
}
function getElementValue() {
var value = selectElement.val();
if ($.isNumeric(value)) {
return Number(value);
} else {
return value;
}
}
}
app.controller('test', function() {
var $ctrl = this
$ctrl.disabled = false
$ctrl.currVal = 2
})
<div ng-app="app" ng-controller="test as $ctrl">
<button ng-click="$ctrl.disabled = !$ctrl.disabled">Toggle</button>
<button ng-click="$ctrl.currVal = 1">Change Value</button>
<code>{{$ctrl.currVal}}</code>
<select-picker disable="$ctrl.disabled" ng-model="$ctrl.currVal">
<select>
<option value="1">Mustard</option>
<option value="2">Ketchup</option>
<option value="3">Relish</option>
</select>
</select-picker>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment