jsFiddle Example: Managing Nested Data in AngularJS

AngularJS Logo

So I've been having problems finding the time to construct a proper blog posting about what I'm working on and learning right now, but I'm also generating a lot of small jsFiddle examples of how to do certain things for other developers. I'm going to try to start linking those things here, so even if I can't explain the code, you can get in and take a look.

That said, here is my first example: how to handle the display of nested data in AngularJS. One of the things that jQuery heavy developers are used to doing is getting in there and manipulating the DOM directly and adding new content. AngularJS flips that on its head and says, essentially: "Do nothing to the DOM after load, only touch the data.". Click below to see an example of that.



Rick Mason's Gravatar Jon,

Just wanted to let you know the tips are appreciated, keep them coming.
Jon Hartmann's Gravatar @Rick, Thanks! I means a lot to hear that. Hopefully this new format will let me post more frequently.
Shail's Gravatar Hi Jon,

I wanted to add dynamic children using form. I have added <input type="text" ng-model="name"> just above the button <button ng-click="add(item)">Add</button> and on app js I have changed "name : 'Child ' + count" to "name : $scope.name".

Why it is not working?

Please help.

Thanks in advance.
Jon Hartmann's Gravatar Hey Shail,

So, it looks like when you get inside an ng-repeat, Angular creates an isolated scope - we are passing the array "List" into the scope when we use it in the ng-repeat attribute. If you're adding a new input field right above the "add" button then its inside the repeat directive. Each iteration of the directive has to be getting an isolated scope because otherwise they should all be bound to the same "name" value - so when you type in one, the other 2 would update as well (the same thing would happen if your original version had worked, all three would be bound to the same "name").

It does look like the add() method does some scope escaping, but since "item" is passed it its not too worried about that.

To do what you want to do, you might be better off setting your input's model to be like "item.childName" and then in your add method using item.childName - and then you will have to clear "item.childName" or it will persist even after adding the child.
Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me.

Post a job. Find one. authenticjobs.com

Interested in becoming a sponsor? Contact me.