Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Using "this" in an interval function within a service

How can I get the "this" keyword working for periodicFetch() when it's called via $interval?

This is the code of my angular application:

angular.module('myapp', []);

var MyService = function($rootScope, $http, $interval) {
    this.variables = {};

    this.registerVariable = function(varName) {
        this.variables[varName] = null;
    };

    this.periodicFetch = function() {
        console.log(this.variables);
    };

    this.run = function() {
        this.periodicFetch();
        $interval(this.periodicFetch, 1000);
    };
};

angular.module('myapp').service('myService',
        ['$rootScope', '$http', '$interval', MyService]);

angular.module('myapp').run(function(myService) {
    myService.registerVariable('foo');
    myService.run();
});

Currently the output is:

Object {foo: null}
undefined
undefined
undefined
...

It seems to work for the first invocation without $interval. But within $interval the value of this.variables seems to be undefined.

like image 410
dubbaluga Avatar asked Dec 19 '22 00:12

dubbaluga


1 Answers

Try use .bind, like so

$interval(this.periodicFetch.bind(this), 1000);

Example

like image 85
Oleksandr T. Avatar answered Dec 24 '22 02:12

Oleksandr T.