2014-03-30 20 views
1

我遇到以下代码的问题。我需要在$timeout or callback from $http之后引用this.counter,但它没有定义,所以请在这里给我一个灯光。范围在AngularJS服务回调中丢失

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(); 
    }); 
}); 

这里是JSFiddle,您将在控制台中看到该操作。

回答

1

使用普通的鬼把戏:

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; 
} 
+0

哦,太感谢你了。如果我们想用$ q来做什么呢? – Devyn

+0

不确定你的意思。 –