2015-05-19 19 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/