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. 
Try use .bind, like so 
$interval(this.periodicFetch.bind(this), 1000);
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With