[英]Creating an ajax loading spinner using a directive in Angularjs
I'm trying to create a simple loader. 我正在尝试创建一个简单的加载器。 Below is what I have done so far. 以下是我到目前为止所做的工作。 Could someone please take a look and let me know where I'm going wrong? 有人可以看看,让我知道我哪里出错了吗?
It appears the CSS styles loading style-2
are not being added. 似乎没有添加CSS样式loading style-2
。 my DOM just shows: 我的DOM只显示:
<span class=""></span>
My directive: 我的指示:
angular.module('loaderModule', [
'restangular',
])
.controller('appLoaderController', ['$scope', function ($scope) {
$scope.$on('LOAD', function () {
$scope.loading = "loading style-2"
});
$scope.$on('UNLOAD', function () {
$scope.loading = ""
});
}])
.directive('spinLoader', function() {
return {
restrict: 'E',
transclude: true,
template: '<span class="{{ loading }}"></span><div ng-transclude ></div>'
};
});
HTML: HTML:
<spin-loader>
<div ui-view></div>
</spin-loader>
I then just use it by calling: $scope.$emit('LOAD')
然后我通过调用它来使用它: $scope.$emit('LOAD')
I would make use of ng-class in your directive like this: 我会在你的指令中使用ng-class,如下所示:
app.directive('spinLoader', function() {
return {
restrict: 'E',
transclude: true,
template: '<div ng-class="{loading: isLoading, style2: isLoading}" ng-transclude></div>'
};
});
In your controller you can then set $scope.isLoading
to be true or false. 在控制器中,您可以将$scope.isLoading
设置$scope.isLoading
true或false。
app.controller('Ctrl', function ($scope) {
var dummyLoadingVariable = false;
$scope.$on('LOAD', function () {
$scope.isLoading = true;
});
$scope.$on('UNLOAD', function () {
$scope.isLoading = false;
});
$scope.toggleLoading = function(){
dummyLoadingVariable = !dummyLoadingVariable;
if(dummyLoadingVariable){
$scope.$emit('LOAD');
} else {
$scope.$emit('UNLOAD')
}
}
});
And the HTML to test it: 和HTML测试它:
isLoading: {{ isLoading }}
<br/>
<spin-loader>
<div ui-view>Transcluded</div>
</spin-loader>
<br/>
<button ng-click="toggleLoading()">toggleLoading()</button>
Here's a Plunk with it running: http://plnkr.co/edit/SetecF03aY6TnQilryWt?p=preview 这是一个正在运行的Plunk: http ://plnkr.co/edit/SetecF03aY6TnQilryWt?p =preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.