Reputation: 2285
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.
Upvotes: 1
Views: 727
Reputation: 692161
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;
}
Upvotes: 1