使用Angularjs中的指令创建ajax加载微调器

Pro*_*eus 5 javascript angularjs

我正在尝试创建一个简单的加载器.以下是我到目前为止所做的工作.有人可以看看,让我知道我哪里出错了吗?

似乎loading style-2没有添加CSS样式.我的DOM只显示:

<span class=""></span>
Run Code Online (Sandbox Code Playgroud)

我的指示:

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>'
    };
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<spin-loader>
    <div ui-view></div>
</spin-loader>
Run Code Online (Sandbox Code Playgroud)

然后我通过调用它来使用它: $scope.$emit('LOAD')

Cra*_*gan 1

我会在你的指令中使用 ng-class ,如下所示:

    app.directive('spinLoader', function() {
        return {
            restrict: 'E',
            transclude: true,
            template: '<div ng-class="{loading: isLoading, style2: isLoading}" ng-transclude></div>'
        };
    });
Run Code Online (Sandbox Code Playgroud)

然后您可以在控制器中将其设置$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')
            }
        }

    });
Run Code Online (Sandbox Code Playgroud)

以及测试它的 HTML:

isLoading: {{ isLoading }}
<br/>
<spin-loader>
    <div ui-view>Transcluded</div>
</spin-loader>

<br/>
<button ng-click="toggleLoading()">toggleLoading()</button>
Run Code Online (Sandbox Code Playgroud)

这是一个正在运行的 Plunk:http://plnkr.co/edit/SetecF03aY6TnQilryWt ?p=preview