服务或工厂中的$ rootScope。$ on

时间:2015-01-20 16:40:50

标签: javascript angularjs

我对服务或工厂中的$rootScope.$on方法有一个奇怪的问题。

我有服务:

app.service('testService', function($rootScope){

this.var1 = 5;

this.change = function(n){
    this.var1 = n;
}

$rootScope.$on('service', function(event, n){
    //this.var1 = n;
    console.log(this.var1);

});
});

问题是应该在控制台中打印5。但我无法在$rootScope.$on方法中访问服务的变量...

她是控制者:

app.controller( 'HelloCtrl', function($scope, testService, testFactory, $rootScope)
{
$scope.fromService = testService;

$rootScope.$broadcast("service", 12);
});

JSFiddle:jsFiddle

问题是什么?

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您需要将this存储在另一个变量中以进行关闭。

内部回调this是另一个......

希望它会对你有所帮助:

//angular.js example for factory vs service
var app = angular.module('myApp', []);
    
app.service('testService', function($rootScope){

    var testService = this;
    
    this.var1 = 5;
    
    this.change = function(n){
        this.var1 = n;
    }
    
    $rootScope.$on('service', function(event, n){
        //this.var1 = n;
        console.log(testService.var1);
       
    });
});

app.controller( 'HelloCtrl', function($scope, testService, $rootScope)
{
    $scope.fromService = testService;

    $rootScope.$broadcast("service", 12);
});

http://jsfiddle.net/mc4ow2b6/4/