AngularJs:使用service传递$ scope变量 [英] AngularJs: pass $scope variable with service
问题描述
我有两个控制器,其中一个我声明了一个$ scope变量,我希望在第二个控制器中可见。
I have two controllers and in one of them I declared a $scope variable that I would like visible in the second controller.
第一个控制器
app.controller('Ctrl1', function ($scope) {
$scope.variable1 = "One";
});
第二个控制器
app.controller('Ctrl2', function ($scope, share) {
console.log("shared variable " + share.getVariable());
});
我研究了最好的Angular方法,我发现这是使用服务。所以我为 Ctrl1添加了一项服务
I researched the best Angular approach and I found that is the use of service. So I added a service for Ctrl1
服务
.service('share', function ($scope) {
return {
getVariable: function () {
return $scope.variable1;
}
};
});
此代码返回此错误:
Unknown provider: $scopeProvider <- $scope <- share
<那么我的问题是:可能在控制器之间共享$ scope变量吗?是不是最好的Angular解决方案或者我错过了什么?
So my question is: is possible share $scope variable between controllers? Is not the best Angular solution or i'm missing something?
对不起我的琐碎问题,但我是一名Angular初学者。
Sorry for my trivial question but I'm an Angular beginner.
提前致谢
问候
推荐答案
您不能在服务工厂函数中注入 $ scope
依赖项。
You cannot inject $scope
dependency in service factory function.
基本上,可共享服务应维护某些对象中的可共享数据。
Basically shareable service should maintain shareable data in some object.
服务
.service('share', function () {
var self = this;
//private shared variable
var sharedVariables = { };
self.getSharedVariables = getSharedVariables;
self.setVariable = setVariable;
//function declarations
function getSharedVariables() {
return sharedVariables;
}
function setVariable() {
sharedVariables[paramName] = value;
}
});
控制器
app.controller('Ctrl1', function ($scope, share) {
$scope.variable1 = "One";
share.setVariable('variable1', $scope.variable1); //setting value in service variable
});
app.controller('Ctrl2', function ($scope, share) {
console.log("shared variable " + share.getSharedVariables());
});
这篇关于AngularJs:使用service传递$ scope变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!