There are some times when you might want to dynamically add elements to the page in response to some user action. Maybe you’re writing a form builder app, and users can add chunks of the form one at a time.
In this case, you want the order of the displayed forms to match the order of the button clicks. So if you have 3 buttons (A, B, C) and the user clicks (B, C, A), then you want form B to be added first, then C, then A.
Here’s an example that works this way. Try clicking the buttons.
The controller has an array of form template names. When a button is clicked, the matching form template name is added to an array of displayed forms. An ng-repeat directive loops array over the list of displayed forms, and uses ng-include to render the templates.
The HTML is simple, and for sake of making it easy to understand, it includes some inline templates. In a real app you’d probably want to put these in files and integrate them into your build process.
The JS code is very simple. All it needs to do is add items to an array when the user clicks buttons.
One important thing to notice with this approach is that you need to use the “track by” syntax (in this case,
track by $index) if you want to allow repeat values - otherwise you’ll get an error saying “Duplicates in a repeater are not allowed.”
If you don’t want to allow repeats, just check before adding each form to the displayedForms array.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, check out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Dave Ceddia’s Pure React is a work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.