Lorenzo von Matterhorn Lorenzo von Matterhorn - 4 months ago 14
AngularJS Question

Setting Nested Object Values from AngularJS Controller

I am trying to set a value of a nested object from my Angular Controller but I keep getting the following error:

Cannot read property 'field0' of undefined


The code in my Controller is:

$scope.obj = $scope.obj || {};

$scope.autosave = function(){
$window.sessionStorage.setItem("experienceOne", $scope.obj.experience.field0);
}


Any idea what I am doing wrong? Im sure its something small but I can't seem figure it out. How can I set the value in a nested object. Just for reference the object structure is like this:

obj{
name:"",
experience:{
field0:"",
field1:"",
field2:""
}
}

Answer

You don't set experience property in default branch. So obj.experience.something throws because experience is undefined. It should be

$scope.obj = $scope.obj || {experience: {}}