0

I have my object

$scope.obj = {
    id : 0,
    name : 'parent',
    childs : [{
        obj_id : $scope.obj.id,
        name : 'child1',
    }, {
        obj_id : $scope.obj.id,
        name : 'child2',
    }]
}

if I change the ID attribute of my $scope.obj dynamically with an input it won't update the obj_id value of my child's objects.

<input type="text" ng-model="obj.id" />

But if I add a new object within the childs attribute like this after having updated the $scope.obj.id value

$scope.obj.childs.push({
    obj_id : $scope.obj.id,
    name : 'child3',
});

the obj_id attribute of my recently child object push will have the new value of $scope.obj.id set in with the input.

Thank you in advance.

1 Answer 1

1

When you assign the parent object's id to the children in the array, it is the value of the id that is copied. So the ng-model on your input tag does not bind to the children's obj_id property at all.

Here is a much more thorough explanation of the problem:

Binding to Values

Perhaps what you need is a property on each child that references the parent object? That way you could get the parent's id from any child object.

$scope.obj = {
    id : 0,
    name : 'parent',
    childs : []
};
$scope.obj.childs.push({
    parent : $scope.obj,
    name : 'child1',
});
$scope.obj.childs.push({
    parent : $scope.obj,
    name : 'child2',
});
Sign up to request clarification or add additional context in comments.

1 Comment

I agree with your second solution. Thanks for the link it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.