AngularJS服务回调中的作用域丢失

AngularJS服务回调中的作用域丢失,angularjs,angularjs-service,Angularjs,Angularjs Service,我对下面的代码有问题。我需要在$timeout或$http的回调后引用此。计数器,但它未定义,因此请在此处为我指示灯 var myApp = angular.module('myApp',[]); myApp.service('myFabricService', function($q,$timeout){ this.counter = 1; this.getMessages = function() { $timeout(function() {

我对下面的代码有问题。我需要在
$timeout或$http的回调后引用
此。计数器
,但它未定义,因此请在此处为我指示灯

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();
    });
});
var myApp=angular.module('myApp',[]);
myApp.service('myFabricService',函数($q,$timeout){
这个计数器=1;
this.getMessages=函数(){
$timeout(函数(){

console.log(this.counter);//使用通常的肮脏技巧:

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;
}
this.counter=1;
this.getMessages=函数(){
var=这个;
$timeout(函数(){

console.log(that.counter);//哦,非常感谢。如果我们想使用$q呢?不知道你的意思。