页面经常会有按钮点击操作,当用户点击的时候,由于网络或者其他原因导致不能很快响应,就得加一个加载动画显示此时的状态。
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="./node_modules/font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="./bootstrap.css" rel="stylesheet">
<script src="./jquery-2.1.1.min.js"></script>
<script src="./angular.js"></script>
</head>
<body ng-controller="myCtrl">
<button class="btn btn-primary" btn-loading-title="导出中,请稍等" trigger-loading="beginLoading" ng-click="toggleLoad()"><i class="fa fa-heartbeat"></i> load</button>
<button class="btn btn-default" ng-click="toggleLoad()">切换按钮状态</button>
</body>
<script>
/*
dependencies:
font-awesome: "^4.7.0",
AngularJS v1.5.0
jQuery v2.1.1
*/
angular.module('myDirectives', [])
.directive('triggerLoading', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
var d = '<i class="fa fa-spinner fa-pulse" style="padding:0"></i>';
var oldI = $(element).find('i.fa');
var text = attr.btnLoadingTitle || '操作中,请稍等';
scope.$watch(function() {
return scope.$eval(attr.triggerLoading);
}, function(value) {
if (angular.isDefined(value)) {
if (value) {
$(element).find('i.fa').remove();
$(element).attr('disabled', true);
$(element).attr('title', text);
$(element).prepend(d);
} else {
$(element).removeAttr('disabled');
$(element).removeAttr('title');
$(element).find('i.fa').remove();
$(element).prepend(oldI);
}
}
});
}
}
});
angular.module('myApp', ['myDirectives'])
.controller('myCtrl', ['$scope', function($scope) {
console.log()
$scope.beginLoading = false;
$scope.toggleLoad = function() {
console.log($scope.beginLoading)
$scope.beginLoading = !$scope.beginLoading;
};
}]);
</script>
</html>