我有两个 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) {
}
}
})
对于我 60% 的东西,我只是在 ctrl1 上调用
save
,然后调用服务保存方法现在有些情况下,在保存之前我需要做一些事情,比如改变一些与一般情况不同的对象参数,我检查 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 );
}]);
如果需要,您还可以将一个服务注入(inject)另一个服务
关于javascript - 我如何访问 Angular 服务中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315283/