Snekse Snekse - 1 year ago 105
AngularJS Question

Reusing Form snippets in AngularJS

What is the best way to go about creating a small bit of HTML Form elements and reusing that as a snippet multiple times in a form, but with different models?

e.g. inputs for firstName, lastName, streetAddress, city, state, zip for student, parent, pointOfContact

If I was hard-coding the model and inputs, I would have something like:

<input name="student.firstName" ng-model="student.firstName" >
<input name="student.lastName" ng-model="student.lastName" >
<input name="parent.firstName" ng-model="parent.firstName" >
<input name="parent.lastName" ng-model="parent.lastName" >
<input name="pointOfContact.firstName" ng-model="pointOfContact.firstName" >
<input name="pointOfContact.lastName" ng-model="pointOfContact.lastName" >

As a angularJs noob, I'm not sure how to do $modelPrefix.firstName

Template ?

<input name="$modelPrefix.firstName" ng-model="$modelPrefix.firstName" >
<input name="$modelPrefix.lastName" ng-model="$modelPrefix.lastName" >

Answer Source

Wrap each of the reusable HTML components in an Angular Directive. This would allow you to reuse the HTML while still passing in different models to each.

This technique (and others) are explained really will in the videos posted on For your purposes pay close attention to videos 10,11,14 and 15.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download