SMSk
SMSk

Reputation: 705

Call function from service body AngularJS

I have the following question:

I have a page that shows some data, and this data is received from server (i.e. last 20 log entries). I can successfully do that when user clicks something by implementing the right ng-click function, yet I have no idea how to receive this data at the first load of the page.

I've tried the fllowing:

app.service('SidebarConnector', ['$http', '$rootScope', function($http, $rootScope){
    this.log_api_url = 'http://localhost:8000/api/logs';
    this.logData = [];
    this.refreshLogData('1', 'Main');

    this.refreshLogData = function(collector, type){
        $http.post(this.log_api_url, {'what': 'top', 'collector': collector, type: type})
            .then((function(response){
                this.logData = response.data.logData;
                $rootScope.$broadcast("SidebarSet");
            }).bind(this));
    };
}])

But I got the error this.refreshLogData is not a function

I also tried calling this function (refreshLogData(...)) from the body of the controller corresponding to my div with this information like:

SidebarConnector.refreshLogData('1', 'Main');

And it works perfectly. But if the function is defined not in side-service, but inside a controller itself, I get the same error: $scope.refreshLogData is not a function.

Question is: why?

Why can't I call functions in the body of parent entity of that function?

Upvotes: 0

Views: 63

Answers (1)

SMSk
SMSk

Reputation: 705

Because I'm stupid and I should declare functions strictly above their first usage.

Upvotes: 1

Related Questions