سؤال

I'm having problem with following code. I need to reference this.counter after a $timeout or callback from $http but it's undefined so please shad me a light here.

var myApp = angular.module('myApp',[]);

myApp.service('myFabricService', function($q,$timeout){

    this.counter = 1;

    this.getMessages = function() {

        $timeout(function() {
            console.log(this.counter); // <--- this will show undefined
            this.counter++;  // <--- this.counter is undefined

        }, 300);

        return false;
    }
});


myApp.controller('BackgroundCtrl', function($scope,myFabricService) {
    $scope.yourName = "my name";
    $scope.$watch('yourName', function(newvalue, oldvalue) {
        myFabricService.getMessages();
    });
});

Here is JSFiddle and you will see the action in console.

هل كانت مفيدة؟

المحلول

Use the usual dirty trick:

this.counter = 1;

this.getMessages = function() {

    var that = this;
    $timeout(function() {
        console.log(that.counter); // <--- this will show undefined
        that.counter++;  // <--- this.counter is undefined

    }, 300);

    return false;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top