0

I'm busy working on an AngularJS application which gets data from an API. However I'm wondering if there's a possibility to directly invoke a function in the scope AND call it normally.

This is what I have in my controller:

var self = this;
$scope.refreshData = (function() {
    $http({
            method: 'GET',
            url: './test-api/testdata.php'
        })
        .success(function(data) {
            self.apiData = data;
        });
    console.log('Refresh executed');
})();

$interval(function() {
    console.log('Refresh called');
    $scope.refreshData();
}, 60000);

This logs:

Refresh executed
angular.js:13540 TypeError: $scope.refreshData is not a function

I know I can just change it to a normal function and call it with $scope.refreshData(), but I was just wondering if there's a method for it in AngularJS.

Starfish
  • 3,344
  • 1
  • 19
  • 47

1 Answers1

1

$scope.refreshData here is undefined as the value you assigned to it is the value returned by the IIFE. In order for this to work, you should do the following:

var self = this;
($scope.refreshData = function() {
    $http({
            method: 'GET',
            url: './test-api/testdata.php'
        })
        .success(function(data) {
            self.apiData = data;
        });
    console.log('Refresh executed');
})(); 

$interval(function() {
    $scope.refreshData();
    console.log('Refresh called');
}, 60000);

PS: You can read more about it here.

Community
  • 1
  • 1
ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • Read my last sentence of my question. I know it can be done that way, but I was wondering if I could invoke it directly on load and call it later on (in my example in an interval) – Starfish Apr 19 '16 at 10:46
  • Yeah I see, works for me too. Never thought about putting the `(` before the `$scope`. – Starfish Apr 19 '16 at 11:01