如何在角度服务中访问范围

时间:2015-05-19 01:24:01

标签: javascript angularjs controller

我有两个控制器

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. 现在有些情况下,在保存之前我需要做一些像chnaging一些不同于genral案例的对象参数的东西我检查e,g

    if(model == 'User'){
    //Here i do this (sample of code)
        var service = $injector.get('Service2');
        service.save()
    
  3. 现在我的问题出在服务2中,我需要访问var1。我怎么能这样做

2 个答案:

答案 0 :(得分:1)

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

.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 );
}]);

如果需要,您还可以将服务注入其他服务

答案 1 :(得分:0)

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

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

});

这是小提琴:https://jsfiddle.net/ueo9ck8r/