javascript - Angular.js 如何在登录 Controller 中设置常量

标签 javascript angularjs

我有一个简单的登录 Controller ,用于处理应用程序登录过程。在模块级别,我创建了一个如下常量:

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

在我的登录 Controller 中,我传入常量,如下所示:

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

但是当我在这里调用常量时我得到了未定义? 如何处理这个问题的正确方法?还是完全不同地做这件事更好?

然后,当调用其他 Controller 时,我希望能够使用这个新数据:

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

最佳答案

尝试替换:

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

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

并在 Controller 中添加常量service:

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

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

应该可以。

关于javascript - Angular.js 如何在登录 Controller 中设置常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573205/

相关文章:

javascript - 使用 AngularJs 计算名称更改的发生次数

html - CSS Hover 只影响 child 而不影响 parent

javascript - 在 Angular Directive(指令)中使用 require 更新 $watch

单击输入时,JavaScript 显示一个 div?

javascript - 找不到变量 : navigate

javascript - 谷歌应用程序脚本

javascript - 如何使表格可按标题 Angular 排序?

javascript - 如何在 AngularJS 中删除或隐藏数组的键值对

javascript - 在旋转 slider 上悬停时弹出文本框

javascript - jQuery Scroll - 进入/退出滚动区域时触发一次函数