5

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')

Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
Prometheus
  • 32,405
  • 54
  • 166
  • 302
  • you might want to have a look at http://stackoverflow.com/questions/17838708/implementing-loading-spinner-using-httpinterceptor-and-angularjs-1-1-5 – Bhalchandra K Dec 23 '13 at 09:12
  • @Balachandra thats a nice way of doing it for ajax, but I went for a different solution so that I can call the spinner anytime. – Prometheus Dec 23 '13 at 09:15
  • Works fine for me http://jsfiddle.net/Ks2Mq/ – dfsq Dec 23 '13 at 09:26
  • @dfsq I see yes, strange then, but me something else going on here for me then as I just get a blank class – Prometheus Dec 23 '13 at 09:35
  • @dfsq I see the issue now I needed to add in ng-controller="appLoaderController"as you did in your code. thanks – Prometheus Dec 23 '13 at 09:38

1 Answers1

1

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

Craig Morgan
  • 942
  • 2
  • 11
  • 27