Angular: directive with callback - 14493050
http://angularjs.org/
by mrajcok
HTML
<div ng-controller="MyCtrl">
<button wait-button do-stuff="doStuff(cbFn)">button label</button>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('waitButton', function() {
return {
scope: {
doStuff: '&'
},
link: function(scope, element) {
var normalText = element.text();
var callbackFn = function() {
console.log('callback')
element[0].disabled = false;
element.text(normalText);
}
element.bind('click', function() {
element[0].disabled = true;
element.text('Loading...');
// Weird syntax below! Arguments must
// be passed inside an object:
scope.doStuff({
cbFn: callbackFn
});
})
}
}
})
function MyCtrl($scope, $timeout) {
$scope.doStuff = function(callbackFn) {
console.log('doStuff');
// Do stuff here... then call the callback.
// We'll simulate doing something with a timeout.
$timeout(function() {
callbackFn()
}, 2000)
}
}