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,您将在控制台中看到该操作。
哦,太感谢你了。如果我们想用$ q来做什么呢? – Devyn
不确定你的意思。 –