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
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);
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);
You have to instantiate $scope.booking.newExternalUsers=[]
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.
Related
I have a complex variable as an object including 2 times the same object.
if I change a value of the first object part, this will assume to change the value of the second part. is there an explanation? why are the tow keys still connected?!
here is a simple example of my code:
arr1={'a':[],'b':{'b1':'','b2':''}};
arr2={'p1':{...arr1},'p2':{...arr1}};
arr2['p1']['a']=[1,2,3];
console.log(arr2['p2']['a']); // works => []
arr2['p1']['b']['b1']='blabla';
console.log(arr2['p2']['b']['b1']); // doesn't work => 'blabla'
I don't want to write 'B={'b1':{'a':''},'b2':{'a':''}}' because A is a very big object in a separated .js file
A={'a':''};
B={'b1':A,'b2':A};
B['b1']['a']='blabla';
The main reason is that you try to change the object element via its index a instead of changing the object (reference). Step by step,
you ask to find B['bi'], which is A object
and then you ask to set A['a'] to blabla
B['b1'] and B['b2'] point to A
you get "both" changed since it's same instance of A
But if you do B['b1'] = { 'a': 'blabla' }, then you will not get the same result. Because now you are adding a new instance without any connection to A.
- use spread operator will save you from a problem like this
The fundamental idea of the spread operator is to create a new plain object using the own properties of an existing object. So {...obj} creates a new object with the same properties and values as obj
you can do that easily like
A={'a':''};
B={'b1':{...A},'b2':{...A}};
B['b1']['a']='blabla';
console.log(B['b2']); // => '' not 'blabla'
I solved the problem with:
arr2={'p1':JSON.parse(JSON.stringify(arr1)),'p2':JSON.parse(JSON.stringify(arr1))};
I want to create an array like this:
send[1]['conversation_group_id']=1;
But i get an error that cannot set property conversation_group_id of undefined. What am i doing wrong?
Thanks!
Even though you have initialized send with [], which makes it an array, send[1] will be undefined, you will need to initialize it as an object too before you can set a property inside it. At the moment you are trying to set a property of undefined.
var send = [];
console.log(send[1]);
send[1] = {};
send[1]['conversation_group_id']=1;
console.log(send[1]['conversation_group_id']);
Your data structure is an array of objects. To initialize it, you can also do it this way.
send = [null, {conversation_group_id: 1}]
Nothing wrong with #Dij's answer, but just though it's worth mentioning an alternative on how to initialize the structure you're looking for.
This is my object:
var example = {"119":{"bannerId":"119","overlay":"3","type":"1",...},"210":{"bannerId":"210","overlay":"3","type":"1",...},...}
In this way I can very easily access or modify object. For example if I want to add new property I simply call this:
example[119].newProperty = 1;
And very easily access it:
alert(example[119].newProperty)
alert(example[210].type)
By knowing banner id, I can access any data from any scope of code, this is the reason I chose this pattern. The problem is that I need to add new object inside example after it has been created. For example I need to push this into example:
{"30":{"bannerId":"119","overlay":"3","type":"1",...}}
And I don't know if this is possible. Is it? One way to solve this problem would be to use array, so example would be array and each key would carry object, and I could push into array new key with object. But I am not sure if this is proper way because key will start with 200, 300, ... console.log(example) shows undefined for all keys before 200. Is fine to have so many empty keys? Is any other better way?
EDIT:
I realized this can be done also with object. The problem was because I was trying to assign new property directly into new object like this:
example[200].example3 = 2;
guessing it is enough that example object is created. What I was missing is this line:
example[200] = {}
Thanks for answers, it works now!
var example = {};
example["30"] = {"bannerId":"119","overlay":"3","type":"1"}
console.log(example);
If its inside a loop you can also try something like below.
var i = 0;
var example = {};
for (i=0; i<10; i++) {
example[i] = {bannerId : i+1 , someOtherItem : i + "Hello"}
}
console.log(example);
example[30] = {"bannerId":"119","overlay":"3","type":"1",...};
You can always access (and assign) ad hoc keys of objects, even if you didn't define them in the first place.
So for your example you can just do:
example["30"] = {... /*your new object*/...}
It seems that you want to extend your object, you could use jQuery or underscore more or less like this:
$.extend(true, example, { "30": { objectId: "201" }}); // deep copy
If you don't want to use any library simply do:
example["30"] = myObj["30"];
angular.forEach($scope.lista, function(data) {
console.log(data);
$scope.listaCliente = data.listaClienteMaquina;
console.log($scope.listaCliente);
});
being that when I access the array of $ scope.listaCliente, it returns undefined, someone help me? : /
being that when I access the array of $scope.listaCliente, it returns undefined
One thing I am sure of is if $scope.listaCliente is an array then you need to push into it. Currently you are reassigning it every-time your loop runs.
$scope.listaCliente.push(data.listaClienteMaquina);
I hope you also initialized the array outside like
$scope.listaCliente = [];
You are iterating all of the properties of the object $scope.lista instead of the array collection listaClienteMaquina.
You can test it here http://codepen.io/leandroh/pen/RPgvwP
Avoid $watch and use ng-change.
Details in this post http://www.benlesh.com/2013/10/title.html
I have an object which looks like
options = {
offers : $$("div.sonan"),
prev : offers[0],
next : offers[1]
}
where the property prev represent the first element of offers array and next represent
the second element of offers array.
How may I use offers property within the options object
I see that you are defining the array inside the object definition and using that array to fetch elements to define other properties of the options object.
this approach won't work because while parsing the options object first, javascript doesn't know what is offers that is offfers is undefined unless the options object gets parsed.
you can see the below written code for more help.
// define the object
var offs = [1,2,3];
var options = {
offers : offs,
prev : offs[0],
next : offs[1]
};
//fetch values from object
options.offers; // should give u [1,2,3]
Try this.
document.write(option[1])
Change the number at the end to change objects.
option : array name.
offers : object 0.
prev : object 1.
next : object 2.