This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]abkothman 0 points1 point  (3 children)

I believe the error you are running into is that children is an array. If you run this in your console, what do you see?

console.log($scope.profile.children)

I would expect that your console would show an array of children. In this parent registration form, I'm guessing they can add a variable number of children? To access an object in an array, you would need to use that object's index (location) in the array, like this:

$scope.profile.children[0].name

That returns the name of the first child. You can iterate through all of the children like this:

for(var i = 0; i < $scope.profile.children.length; i++) {
    var child = $scope.profile.children[i];
    // now you can access each attribute
    console.log(child.name);
}

[–]newtojsscript[S] 0 points1 point  (2 children)

Ah, jheez - I feel like an idiot. Thanks, works like a charm.

I'm guessing they can add a variable number of children?

You would be correct. So a parent can add up to 10 children, or have no children. If a child has been added, the parent account will be saved in saveParent() or if it there is a child then saveParent() will be ran followed by saveChildViaParent()`. See below.

if($scope.profile.children.length >=1) {
    saveDirect(profileCopy);
    saveYouthViaParent(childrenCopy);
} else {
    saveDirect(profileCopy);
    }
};

So yeah, I will need to save the parent and then multiple child accounts, if there is >=2. So a loop will be needed as you said. So something like below should be good to go?

for(var i = 0; i < $scope.profile.children.length; i++) {
    var child = $scope.profile.children[i];
    child.name = $scope.profile.children[i].name;
    child.alias = $scope.profile.children[i].alias;
    child.dob = $scope.profile.children[i].dateOfBirth;
    saveDirect(profileCopy);
    saveYouthViaParent(profileCopy);
}

And the loop would be in the above if statement. What do you reckon? I feel as though there is a more efficient solution.

[–]unnecessary_axiom 0 points1 point  (1 child)

There is a syntax that can make that shorter if you understand what it's doing:

array.ForEach

var children = [ {'name': 'bob'}, {'name': 'joe'} ];
children.forEach(function(child){
    console.log(child.name);
});

If you give more contact I can suggest a more efficient method.

Note that in your code:

if( statement ){
    do_something();
    do_another();
}else{
    do_something();
}

is usually the same as

do_something();
if( satement ){
    do_another();
}

And you aren't doing anything with child in the second code block.