I'm a beginner in AngularJS, and I have a problem with pushing into an array inside a JSON. (I hope I'm using the correct terminology)
//I have a JSON that looks like this
var items = [
{name:[
{names: 'John', msg:[""]}, {names: 'Dolly', msg:[""]}
]}
];
Below code is inside a Controller:
$rootScope.items = People.list();
$rootScope.name = "John";
for(var i=0;i<$rootScope.items.name.length;i++)
{
if (name== $rootScope.items.name[i].names)
{
People.addcomment(user.comment,i);
}
}
Below code is in my service called 'People':
this.addcomment = function(comment,x) {
items[0].name[x].msg.push(comment);
}
this.list = function () {
return items[0];
}
The JSON is declared in the service. The HTML code is as below:
<textarea placeholder="Enter comment" ng-model="user.comment"></textarea>
<button ng-repeat = "x in items.name" ng-if="name==x.names"
ng-click="addcomment(user,name)">Submit</button>
Now, my problem is that on clicking the 'Submit' button, the 'message' I have typed in the teaxtarea is not getting stored in the 'msg' array corresponding to "John" (inside of the JSON). What is going wrong?
I had the entire code of the Service inside of the Controller earlier, and the code used to work properly then. I suppose I must have done some mistake with the arguments I'm passing to the function in the service.
Could someone please help me out?
So the workflow of you app is as follows:
To keep those two scopes in sync, add a function to your controller:
function updateList() {
$rootScope.items = People.list();
}
Call this method after you call People.addComment().
Lastly, maybe this is just an opinion, you should change your JSON-structure. In gets ways clearer if you set up your data like this:
var items = [
{name: 'John', msg:[]},
{name: 'Dolly', msg:[]}
];
Now you have an array of objects. Your People.list() function now returns items
and you can add a new Person by calling items.push({name: 'Judith', msg:[]});
and you can add a message with items[i].msg.push("This is a new message");