I have an Angular Factory whose job is to save special objects and retrieve them later.
(Used to save the users workflow when he switches views).
Basically I need to save objects with a name, as well as an array of tags. My problem is with the saving the tags into the array part.
The Prototype constructor:
// define the TagsObject constructor function
var TagsObject = function(name, tag) {
this.name = name;
this.tags = [].push(tag);
return this;
};
Full factory code:
.factory('TagFactory', [function() {
// Init TagFactory:
var tagContainers = [];
// define the TagsObject constructor function
var TagsObject = function(name, tag) {
this.name = name;
this.tags = [].push(tag);
return this;
};
console.log('tagFactory');
console.log(TagsObject);
var saveTags = function(name, tag) {
tagContainers.push(new TagsObject(name, tag));
console.log('saveTags:');
console.log(tagContainers);
};
var getTags = function(name) {
console.log(name);
return this;
};
return {
saveTags : saveTags,
getTags : getTags
};
}]);
In a different controller I now save some data into a new Prototype
inside of the TagFactory:
TagFactory.saveTags('TEST', tagObj);
Now back in my Factory, where you see the console.log(nameTagContainers);
the following is the log:
[TagsObject]
0: TagsObject
tags: 1
name: "TEST"
__proto__: TagsObject
length: 1
__proto__: Array[0]
^ tags is an Array, but it's showing 1, instead of the Object details... do you see where I went wrong?
UPDATE: This question was answered below by Kauê Gimenes, however I'm sharing the extra code I added to fix my other problem.
Which was every time a new tag was selected for a currently selected name, it generated a new Prototype, instead of saving the tag into an existing Prototype:
var saveTags = function(name, tag) {
console.log(tagContainers.length);
if (tagContainers.length != 0) {
for(var i = 0; i < tagContainers.length; i++) {
if (tagContainers[i].name == name) {
console.log('Found existing name! Add tag to existing obj');
tagContainers[i].tags.push(tag);
break;
} else {
console.log('New name, create new obj');
tagContainers.push(new TagsObject(name, tag));
}
}
}
else {
console.log('New name, init: create the first obj');
tagContainers.push(new TagsObject(name, tag));
}
console.log(' ');
console.log('tagContainers:');
console.log(tagContainers);
};
Try this approach:
// define the TagsObject constructor function
var TagsObject = function(name, tag) {
this.name = name;
this.tags = [tag];
return this;
};
The best way to initialize an array is to include the elements inside the brackets
[ 1 , 2 , 3 ]
But in case you want to initialize with n elements you could use the concat
function.
[ 1 ].concat([ 2 , 3 , 4 ])
The result would be:
[ 1 , 2 , 3 , 4 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With