我有一个简单的登录 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/