Sergey Kudryashov
Sergey Kudryashov

Reputation: 723

AngularJS call controller from directive with callback

I have a block which I want to update on refresh button click.

<div ng-controller="Ctrl1">
    <ct-paneltool tool-refresh="load1">
        <a href="#" class="btn btn-transparent btn-sm" panel-refresh="" tooltip-placement="top" tooltip="Refresh" data-spinner="load1" ng-click="getData()"><i class="ti-reload"></i></a>
    </ct-paneltool>
    {{ Data }}
</div>

In my contoller I have function

$scope.getData = function(callback){

    $http.get(
      'url',
      {}
    ).then(function (response) {

        $scope.Data = response;
        console.log(callback); // Here returns function anonymous()
        callback();


    });

}

And in my directive I have code

.directive('panelRefresh', function () {
    'use strict';

    return {
        restrict: 'A',
        controller: ["$scope", "$element", function ($scope, $element) {

            var refreshEvent = 'panel-refresh', csspinnerClass = 'csspinner', defaultSpinner = 'load1';

            function removeSpinner() {
                this.removeClass(csspinnerClass);
            }

            $element.on('click', function () {


                var $this = $(this), panel = $this.parents('.panel').eq(0), spinner = $this.data('spinner') || defaultSpinner;
                panel.addClass(csspinnerClass + ' ' + spinner);

                $scope.getData( function(){
                    // attach as public method
                    panel.removeSpinner = removeSpinner;

                    // Trigger the event and send the panel object
                    $this.trigger(refreshEvent, [panel]);
                } );





            });

        }]
    };
});

When I click refresh button spinner is appears, getData() loads data but callback doesn't fire. And logging of callback shows 'function anonymous()'

So tell me please what I do wrong? It is my first application with Angular. If I should orginize my code another way, please explain me.

Also, I want to call panelRefresh directive on load. Is it possible?

Upvotes: 0

Views: 543

Answers (1)

Silvio Troia
Silvio Troia

Reputation: 1459

this is your solution

(function ($, window, document) {
    'use strict';

    $(document).on('panel-refresh', '.panel', function (e, panel) {

        // perform any action when a .panel triggers a the refresh event
        setTimeout(function () {
            // when the action is done, just remove the spinner class
            panel.removeSpinner();
        }, 3000);

    });

}(jQuery, window, document));

Upvotes: 1

Related Questions