AngularJS使用服务传递没有$ scope的数据

时间:2014-11-24 19:21:59

标签: angularjs angularjs-scope

我开始使用angularjs,我看到的第一个例子是使用this代替$scope的。

例如

app.controller('TabController',function(){
    this.tab = 1;
});

我正在尝试在控制器之间传递数据。我看到的每个示例都使用一个使用$rootScope的服务,然后广播一个事件。然后控制器使用$scope.$on来监听该事件。

例如

app.service('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.tab = 1;    

    sharedService.setTab= function(tab) {
        this.tab = tab;
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

app.controller('TabController',['$scope','mySharedService',function($scope,mySharedService){
    $scope.tab = 1;
    $scope.$on('handleBroadcast', function() {
        $scope.tab = sharedService.tab;
    });
}]);

我的问题是如何在不使用$scope的情况下执行此操作,而是使用this

1 个答案:

答案 0 :(得分:0)

我接受了@Dieter Goetelen的回答并稍微改了一下

结果:

app = angular.module('app', []);

app.service('SharedService',function(){
  this.counter = {value:0};
  this.add = function (amount){ 
       this.counter.value++;}
  });

app.controller('TabController',['SharedService',function(SharedService){
    this.sharedService = SharedService;
    this.counter = SharedService.counter;

    this.add = function(amount){
        this.sharedService.add(amount);
     }    
}]);

这是完整的plunk