RudziankoŇ≠ RudziankoŇ≠ - 16 days ago 5
Javascript Question

AngularJS: Component and dependence injection

I have following module:

angular.module("individual-footprint")
.controller("individualFootprintController", individualFootprintController)
.value("currentUser");


controller for this module:

function individualFootprintController($http, individualFootprintService, currentUser) {
var self = this;
$http.get("/user").success(function (data) {
if (data.name) {
currentUser = data;
self.authenticated = true;
}
})


And following component:

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;
}
}
});


My html is following:

<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>


Sorry, I am new to AngularJS, and probably I misuse something. My assumption is
.value("currentUser");
is global variable, I can inject it and change it wherever I want. But I get
TypeError: Cannot read property 'name' of undefined
. Could you, please, suggest better solution for my global var?

Answer

You have to define a value as {}(empty object) for your currentUser value variable. Currently you are doing currentUser.name inside component controller where you are trying to access name property from undefined variable since it throws an error TypeError: Cannot read property 'name' of undefined

.controller("individualFootprintController", individualFootprintController)
.value("currentUser", {}); //value currentUser defined as blank object
Comments