jsFiddle Example: Managing Nested Data in AngularJS
- July 2, 2014 9:36 AM
- AngularJS, Examples & Tutorials, Javascript
- Comments (4)
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.
Comments
Just wanted to let you know the tips are appreciated, keep them coming.
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.
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.