Created
October 31, 2015 10:41
-
-
Save faridprogrammer/5beaa92a461b887373e6 to your computer and use it in GitHub Desktop.
Click and disable directive sample
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body ng-app="apps"> | |
<div ng-controller="myCtrl"> | |
<button click-and-disable="loadData($notify)">Click and disable</button> | |
<br/> | |
{{ text }} | |
</div> | |
<script> | |
var module = angular.module("apps", []); | |
angular.module("apps").controller("myCtrl", function($scope, $timeout){ | |
$scope.loadData = function($notify) { | |
$scope.text = ''; | |
$timeout(function() { | |
$scope.text = 'data loaded!'; | |
$notify && $notify(); | |
}, 1000); | |
}; | |
}); | |
angular.module("apps").directive('clickAndDisable', function($parse, $q, $timeout) { | |
var link = function(scope, elem, attr) { | |
var isNotifyMode = attr.clickAndDisable.indexOf('$notify') > -1; | |
var fn = $parse(attr.clickAndDisable, null, true); | |
var previousText = elem.text(); | |
var disableBtn = function() { | |
elem.text('wait...'); | |
elem.attr('disabled', 'disabled'); | |
}; | |
var enableBtn = function() { | |
elem.text(previousText); | |
elem.attr('disabled', ''); | |
}; | |
elem.on('click', function(event) { | |
scope.$apply(function() { | |
if (isNotifyMode) { | |
disableBtn(); | |
} | |
fn(scope, { | |
$event: event, | |
$notify: function() { | |
enableBtn(); | |
} | |
}); | |
}); | |
}); | |
}; | |
return { | |
link: link, | |
restict: 'A', | |
}; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment