Question

I'd like to create/use an AngularJS directive to avoid creating some redundant HTML and also to simplify how I use Bootstrap elements. I'd like to use a directive this way:

<myDirective id="person.lname" label="Last Name"></myDirective>

The template I'd like AngularJS to write is:

<label for="person.lname">Last Name</label>
<input id="person.lname" name="person.lname" ng-model="person.lname">

How would I declare a directive to be able to create this template and have the binding with ng-model still work? Are there any reasons why this would not be a good idea?

Thanks.

UPDATED

I added the label tag to reflect how the id/name would be used for the input element. The generated template would allow you to click on the label and have the focus be placed on the input element.

Was it helpful?

Solution

This should do what you want:

.directive('myDirective', function() {
  return {
    scope: {
      model: '=identifier',
      id: '@identifier',
      label: '@',
    },
    restrict: 'E',
    template: '<label for="{{id}}">{{label}}</label><input id="{{id}}" name="{{id}}" ng-model="model">'
  };
})

View:

<my-directive label='Last name' identifier="person.lname"></my-directive>

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top