范围在AngularJS服务回调中丢失

时间:2014-03-30 12:50:44

标签: angularjs angularjs-service

我遇到以下代码问题。我需要在this.counter之后引用$timeout or callback from $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();
    });
});

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

1 个答案:

答案 0 :(得分: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;
}