2015-05-19 146 views
2

访问范围,我有两个控制器我怎样才能在角服务

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%我只是叫save上CTRL1其然后称为服务保存方法

  2. 现在有些情况下,在保存之前我需要做一些这样的东西chnaging比GENRAL情况不同对象的一些参数有我检查E,G

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

现在我的问题是服务2我需要访问var1。我怎样才能做到这一点

+0

'$ rootScope'是做到这一点的方法之一。并通过它将是另一回事。 – batmaniac7

回答

1

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

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

您也可以注入一个服务到如果其他服务需要

+0

但这些变量都绑定到控制器的范围。假设var是当前的活动菜单。现在,这意味着我还需要更新服务以及活动菜单 – user2134226

+0

不知道你在寻找什么样的魔术答案。 – charlietfl

+0

是否可以,如果我看着控制器中的变量和更新服务变量。这是人们做事的方式。目前我做到了,但我不确定这是否正确 – user2134226

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/