javascript - Pushing into JSON suddenly not working [RESOLVED] -
i'm beginner in angularjs, , have problem pushing array inside json. (i hope i'm using correct terminology)
//i have json looks var items = [ {name:[ {names: 'john', msg:[""]}, {names: 'dolly', msg:[""]} ]} ]; below code inside 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 in service called 'people':
this.addcomment = function(comment,x) { items[0].name[x].msg.push(comment); } this.list = function () { return items[0]; } the json declared in service. html code 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, problem on clicking 'submit' button, 'message' have typed in teaxtarea not getting stored in 'msg' array corresponding "john" (inside of json). going wrong?
i had entire code of service inside of controller earlier, , code used work then. suppose must have done mistake arguments i'm passing function in service.
could please me out?
so workflow of app follows:
- service instantiated, json stored in scope of service
- controller instantiated, copies array people.list() rootscope.items
- the ng-repeats repeats each element in rooscope.items - not each element in items array in people-service
- someone enters new message
- this message added items in service people.addcomment.
- step number 5 changes items in service, not items in rootscope. that's why ng-repeat doesn't add new element.
to keep 2 scopes in sync, add function controller:
function updatelist() { $rootscope.items = people.list(); } call method after call people.addcomment().
lastly, maybe opinion, should change json-structure. in gets ways clearer if set data this:
var items = [ {name: 'john', msg:[]}, {name: 'dolly', msg:[]} ]; now have array of objects. people.list() function returns items , can add new person calling items.push({name: 'judith', msg:[]}); , can add message items[i].msg.push("this new message");
Comments
Post a Comment