AngularJs:通过服务传递 $scope 变量 [英] AngularJs: pass $scope variable with service

查看:27
本文介绍了AngularJs:通过服务传递 $scope 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器,其中一个我声明了一个 $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:通过服务传递 $scope 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆