我有以下模块:
angular.module("individual-footprint")
.controller("individualFootprintController", individualFootprintController)
.value("currentUser");
该模块的控制器:
function individualFootprintController($http, individualFootprintService, currentUser) {
var self = this;
$http.get("/user").success(function (data) {
if (data.name) {
currentUser = data;
self.authenticated = true;
}
})
以下组件:
angular.module("individual-footprint")
.component('employeeInfoComponent', {
template:'Logged in as: <span ng-bind="$ctrl.user"></span>',
controller: function (currentUser) {
if (currentUser.name) {
self.user = currentUser.name;
}
}
});
我的html如下:
<div ng-controller="individualFootprintController as $ctrl">
<div ng-hide="$ctrl.authenticated">
<h1>Login</h1>
With Corporate Account: <a href="/login/corporate">click here</a>
</div>
<div ng-show="$ctrl.authenticated" >
<employee-info-component></employee-info-component>
</div>
抱歉,我是AngularJS的新手,可能是我误用了一些东西。我的假设是.value("currentUser");
是全局变量,我可以将其注入并在任何我想要的地方进行更改。但我得到TypeError: Cannot read property 'name' of undefined
。请问您能为我的全局变量提出更好的解决方案吗?
答案 0 :(得分:2)
您必须为{}
值变量定义值currentUser
(空对象)。目前,您正在组件控制器中执行currentUser.name
,您尝试从name
变量访问undefined
属性,因为它会引发错误TypeError: Cannot read property 'name' of undefined
.controller("individualFootprintController", individualFootprintController)
.value("currentUser", {}); //value currentUser defined as blank object