Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. my DOM just shows:

<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:

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

I then just use it by calling: $scope.$emit('LOAD')

like image 673
Prometheus Avatar asked Nov 10 '22 16:11

Prometheus


1 Answers

I would make use of ng-class in your directive like this:

    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.

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:

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

like image 124
Craig Morgan Avatar answered Nov 14 '22 22:11

Craig Morgan