I have a parent controller, UserEditCtrl and a child controller, EditUserCtrl. Inside of my parent controller I am pulling in a user object via a service:
userMgmtSvc.user(scope.editUserId).then(function(data) {
this.user = data;
});
Then I want to set a property of my user object to another variable.
this.selectedRoles = this.user.roles;
But this throws an error:
Cannot read property 'user' of undefined.
I'm confused as to how I reference objects that are set with this. For example, how do I just console.log the object? Because console.log('user', this.user); returns undefined:
user undefined
Here's the parent controller:
(
function (app) {
/* @fmt: off */
'use strict';
// @fmt:on
app.controller('UserEditCtrl', ['$scope', '$http', 'userMgmtSvc', 'createUserSvc', 'authSvc', '$state', '$timeout', '$location', '_',
function (scope, http, userMgmtSvc, createUserSvc, authSvc, state, timeout, location, _) {
userMgmtSvc.user(scope.editUserId.id || sessionStorage.getItem('editUser')).then(function(data) {
this.user = data;
console.log('user', this.user);
// GET states
createUserSvc.states().then(function(data) {
this.states = data;
console.log(this.states);
});
// GET countries
createUserSvc.countries().then(function(data) {
this.countries = data;
});
// GET roles
createUserSvc.roles().then(function(data) {
this.roles = data;
});
// GET insurance groups
createUserSvc.insuranceGroups().then(function(data) {
this.insuranceGroups = data;
});
this.selectedRoles = this.user.roles;
});
}]);
}(window.app)
);
thencallback,thisprobably does not refer to the controller. See How to access the correctthis/ context inside a callback?. In addition, at the moment you are trying to readthis.user.roles, thethencallback most likely hasn't been executed yet, so the value couldn't have been set, even ifthisreferred to the correct objects. To help you better, you'd have to provide a complete* example, as described here: stackoverflow.com/help/mcve - Felix Kling.bind()the function in thethen()tothisso that it would be the correct keyword. - Jhecht