【问题标题】:Creating an ajax loading spinner using a directive in Angularjs使用 Angularjs 中的指令创建 ajax 加载微调器
【发布时间】:2014-03-05 17:06:02
【问题描述】:

我正在尝试创建一个简单的加载程序。以下是我到目前为止所做的。有人可以看看,让我知道我要去哪里错了吗?

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

<span class=""></span>

我的指令:

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:

<spin-loader>
    <div ui-view></div>
</spin-loader>

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

【问题讨论】:

  • @Balachandra 这对于 ajax 来说是一种很好的方法,但我选择了不同的解决方案,以便我可以随时调用微调器。
  • 对我来说很好jsfiddle.net/Ks2Mq
  • @dfsq 我明白了,那很奇怪,但是我这里还有其他事情发生,因为我只是得到一个空白课程
  • @dfsq 我现在看到了这个问题,我需要像在代码中那样添加 ng-controller="appLoaderController" 。谢谢

标签: javascript angularjs


【解决方案1】:

我会像这样在你的指令中使用 ng-class:

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

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

    });

以及测试它的 HTML:

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

<br/>
<button ng-click="toggleLoading()">toggleLoading()</button>

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

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多