我如何访问 angular 服务中的范围

How can i access scope in angular service

我有两个控制器

app.controller('TestCtrl1', ['$scope', function ($scope) {
    $scope.save = function () {
        console.log("TestCtrl1 - myMethod");
    }
}]);



 app.controller('TestCtrl2', ['$scope', function ($scope) {
$scope.var1 = 'test1'        

$scope.save = function () {
            console.log("TestCtrl1 - myMethod");
    }
}]);

那我有两个服务

.service('Service1', function($q) {
    return {
        save: function(obj) {
       }
    }
})

.service('Service2', function($q) {
    return {
        save: function(obj) {
       }
    }
})
  1. 对于我 60% 的东西,我只是在 ctrl1 上调用 save,然后调用服务保存方法

  2. 现在在某些情况下,在保存之前我需要做一些事情,比如更改一些与一般情况不同的对象参数,我检查 e,g

    if(model == 'User'){
    //Here i do this (sample of code)
        var service = $injector.get('Service2');
        service.save()
    

现在我的问题出在服务 2 中,我需要访问 var1。我该怎么做

使用服务本身共享变量作为服务对象的一部分以及每个服务的方法

.service('Service2', function($q) {
    var self = this;
    this.var1 = 'test1';
    this.save = function(obj) {            
    }

});

app.controller('TestCtrl2', ['$scope','Service1','Service2', function ($scope, Service1, Service2, ) {
     // bind scope variable to service property
     $scope.var1 = Service2.var1;       
     // add a service method to scope
     $scope.save = Service1.save;
     // now call that service method
     $scope.save( $scope.var1 );
}]);

如果需要,您还可以将一个服务注入另一个服务

将服务注入其他服务(一种可能的方法):

html:

<div id="div1" ng-app="myApp" ng-controller="MyCtrl">

    <!--to confirm that the services are working-->
     <p>service three: {{serviceThree}}</p>  

</div>

js:

angular.module('myApp',[])

.service('s1', function() {
    this.value = 3;
})

.service('s2', function() {
    this.value = 10;
})

.service('s3', function(s1,s2) {     //other services as dependencies
    this.value = s1.value+s2.value;  //13   

})
.controller('MyCtrl', function($scope, $injector) {  //$injector is a dependency

    $scope.serviceThree = $injector.get('s3').value; //using the injector

});

这是 fiddle:https://jsfiddle.net/ueo9ck8r/