Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created June 30, 2015 13:15
Show Gist options
  • Save kentcdodds/386ef4de3166bd267184 to your computer and use it in GitHub Desktop.
Save kentcdodds/386ef4de3166bd267184 to your computer and use it in GitHub Desktop.
Example of a button-group for angular-formly
<div class="btn-group btn-group-justified button-group">
<div class="btn-group" ng-repeat="(key, option) in to.options">
<button class="btn az-btn grouped-button"
ng-class="{'btn-primary': model[options.key || index] === option.value, 'btn-default': model[options.key || index] !== option.value}"
value="{{option.value}}"
role="radio"
ng-model="model[options.key]"
btn-radio="option.value">{{::option.name}}</button>
</div>
</div>
const angular = require('angular');
export default ngModule => {
const template = require('./button-group.html');
ngModule.run(function(formlyConfig) {
formlyConfig.setType({
name: 'button-group',
template,
extends: 'azBase',
data: {
styles: require('./button-group.less')
},
link(scope, el) {
el.on('keyup', function(e) {
/* eslint default-case:0 */
switch (e.which) {
case 37:
case 38:
return moveFocus(-1);
case 39:
case 40:
return moveFocus(1);
}
});
function moveFocus(amount) {
const currentValue = scope.model[scope.options.key || scope.index];
let index = 0;
scope.to.options.some(function(option, i) {
if (option.value === currentValue) {
index = i;
return true;
}
});
let newFocus = index + amount;
if (newFocus < 0) {
newFocus = scope.to.options.length - 1;
} else if (newFocus >= scope.to.options.length) {
newFocus = 0;
}
const button = angular.element(el.find('button')[newFocus]);
scope.model[scope.options.key || scope.index] = button.attr('value');
button.focus();
button.click();
scope.$digest();
}
}
});
});
};
.component(formly-field, {
.component(grouped-button, {
&:focus {
@borderColor: darken(@btn-primary-bg, 17%);
background-color: @borderColor;
border-color: darken(@borderColor, 14%);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment