Skip to content

Instantly share code, notes, and snippets.

@gpolanco
Last active December 27, 2017 09:48
Show Gist options
  • Save gpolanco/82cf3365e6b6dba0cc5226ba95a48d77 to your computer and use it in GitHub Desktop.
Save gpolanco/82cf3365e6b6dba0cc5226ba95a48d77 to your computer and use it in GitHub Desktop.
/* Simple directiva para generar un botón con spinner.
Uso:
<button-loading on-search="$ctrl.buscar()" isloading="functionRequest()" type="btn-default"></button-loading>
Required params: ['onSearch', 'isloading']
*/
// Button loading directive
//------------------------------------------------------------
app.directive('buttonLoading', function () {
var _TEXTS = {
LOADING_PARAM_ERROR: 'ERROR: El parámetro \"isloading\" es obligatorio. Es necesario para mostrar el spinner.',
ONSEARCH_PARAM_ERROR: 'ERROR: El parámetro \"onSearch"\ es obligatorio. Es la función que hace la llamada a HTTP.',
}
return {
template: '<button ng-click="onSearch()" class="btn {{type}} {{size}}" data-loading-text="{{loadtext}}">' +
'<i class="fa {{icon}}"></i> <span class="hidden-xs">{{ text }}</span>' +
'</button>',
restrict: 'E',
replace: true,
require: ['onSearch', 'isloading'],
scope: {
icon : '@',
type : '@',
size : '@',
text : '@',
loadtext : '@',
isloading : '=',
onSearch : '&'
},
link: function (scope, $element, $attrs) {
var default_loading_icon = '<i class="fa fa-spinner fa-pulse fa-fw"></i>';
scope.icon = $attrs.icon || 'fa-search';
scope.type = $attrs.type || 'default';
scope.size = $attrs.size || '';
scope.text = $attrs.text || '';
scope.loadtext = $attrs.loading || default_loading_icon;
// isloading parameter is mandatory
//----------------------------------------
if (scope.isloading === undefined) return console.warn(_TEXTS.LOADING_PARAM_ERROR);
console.log(typeof (scope.onSearch))
// onSearch parameter is mandatory : type function
//------------------------------------------------
if (scope.onSearch === undefined) return console.warn(_TEXTS.ONSEARCH_PARAM_ERROR);
// start/stop loading icon
//-----------------------------------------
scope.$watch('isloading', function () {
if (scope.isloading) {
$element.button('loading');
} else {
$element.button('reset');
}
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment