当前位置:  开发笔记 > 编程语言 > 正文

Angular.js如何在登录控制器中设置常量

如何解决《Angular.js如何在登录控制器中设置常量》经验,为你挑选了1个好方法。

我有一个简单的登录控制器来处理应用程序登录过程.在模块级别,我创建了一个这样的常量:

.constant('MyConstant', [{
    id: null,
    user: null
}])

在我的登录控制器中,我传递常量,如下所示:

.controller('loginController', [
    '$scope',
    'MyConstant',
    function ($scope, MyConstant) {
        //here i want to change the constants data like this:
        MyConstant.user = 'My new username'
    }
])

但是当我在这里调用常量时,我​​得到了未定义的?如何正确处理这个问题?或者这样做完全不同更好吗?

然后在调用其他控制器时,我希望能够使用这些新数据:

 .controller('otherController', [
         '$scope',
         'MyConstant',
        function ($scope, MyConstant) {
            //this should return 'My new username'
            console.log(MyConstant.user);
        }
    ])

Avnesh Shaky.. 5

尝试替换:

.constant('MyConstant', [{
    id: null,
    user: null
}])

.constant('MyConstant', {
    id: null,
    user: null
})

service在控制器中添加常量:

.controller('otherController', [
    '$scope', 'MyConstant',
    function ($scope, MyConstant) {
        //this should return 'My new username'
        console.log(MyConstant.user);
    }
])  

并用作共享服务(在root中定义),以便可以在任何控制器(整个应用程序)中使用

应该管用.



1> Avnesh Shaky..:

尝试替换:

.constant('MyConstant', [{
    id: null,
    user: null
}])

.constant('MyConstant', {
    id: null,
    user: null
})

service在控制器中添加常量:

.controller('otherController', [
    '$scope', 'MyConstant',
    function ($scope, MyConstant) {
        //this should return 'My new username'
        console.log(MyConstant.user);
    }
])  

并用作共享服务(在root中定义),以便可以在任何控制器(整个应用程序)中使用

应该管用.

推荐阅读
虎仔球妈_459
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有