$rootScope.$on 在服务或工厂中

$rootScope.$on in a service or factory

本文关键字:工厂 rootScope on 服务      更新时间:2023-09-26

我在服务或工厂中的$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

怎么了?

我该怎么办?

您需要将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/