AngularJS使用服务传递不带$scope的数据

AngularJS使用服务传递不带$scope的数据,angularjs,angularjs-scope,Angularjs,Angularjs Scope,我开始使用angularjs,我看到的第一个示例是使用这个而不是$scope的示例 比如说 app.controller('TabController',function(){ this.tab = 1; }); app.service('mySharedService', function($rootScope) { var sharedService = {}; sharedService.tab = 1; sharedService.setTa

我开始使用angularjs,我看到的第一个示例是使用这个而不是$scope的示例

比如说

app.controller('TabController',function(){
    this.tab = 1;
});
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;
    });
}]);
我正在尝试在控制器之间传递数据。我看到的每个示例都使用一个使用$rootScope的服务,然后广播一个事件。然后,控制器使用$scope.$on来侦听该事件

比如说

app.controller('TabController',function(){
    this.tab = 1;
});
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的情况下做到这一点,而是使用它。

我接受了@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。使用它不会阻止您使用$scope、$rootScope或两者兼用。@Dieter谢谢,它看起来正是我所需要的。@jbnize不要查看Dieter评论很高兴我能帮您找到解决方案。