0

I have a form that uses $scope.booking variable composed of several fields and array, all loaded from HTML. I need to add an array of object from javascript, adding one object per time. I tryed

$scope.booking.newExternalUsers[$scope.count]= $scope.user.newExternalUser;

and

$scope.booking.newExternalUsers.push=$scope.user.newExternalUser;

but I receive Cannot set property '0' of undefined and Cannot set property of undefined, it is correct because I have instantiated only $scope.booking={} Maybe is a stupid question, but I am almost new in angularjs, how can I add the $scope.user.newExternalUser one pertime (for each button event)?. Thanks

4 Answers 4

2

You should define the array first before set values to it.

like this:

$scope.booking = {};

$scope.booking.newExternalUsers = [];

or

$scope.booking = {
    newExternalUsers: []
};

Then

You can add items to it as you want, like this:

$scope.booking.newExternalUsers[$scope.count]= $scope.user.newExternalUser;

or using Array.prototype.push()

$scope.booking.newExternalUsers.push($scope.user.newExternalUser);

Sign up to request clarification or add additional context in comments.

Comments

1

First define the property newExternalUsers in booking array first

$scope.booking={
  'newExternalUsers' : []
}

or

$scope.booking.newExternalUsers=[]

Then push the item to an booking array

$scope.booking.newExternalUsers.push($scope.user.newExternalUser);

Comments

0

You have to instantiate $scope.booking.newExternalUsers=[]

2 Comments

it creates a different object
@luca You have to define newExternalUsers as an Array first, before you can use it. The undefined error is because your $scope.booking object doesn't have the newExternalUsers property defined.
0

I'll assume you have a controller. In that controller you can have this:

$onInit() {
  this.booking = { newExternaUsers: [] };
}

Then it's initiated once when the controller starts.

Comments

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.