Johann
Johann

Reputation: 29867

What is the purpose of the "for" attribute?

In this code taken from angular.org:

<script>
   function Ctrl($scope) {
     $scope.names = ['pizza', 'unicorns', 'robots'];
     $scope.my = { favorite: 'unicorns' };
   }
</script>
 <form ng-controller="Ctrl">
   <h2>Which is your favorite?</h2>
     <label ng-repeat="name in names" for="{{name}}">
       {{name}}
       <input type="radio"
              ng-model="my.favorite"
              ng-value="name"
              id="{{name}}"
              name="favorite">
     </label>
   <div>You chose {{my.favorite}}</div>
 </form>

the label element has a "for" statement. I can't find anything on the Angular.org site indicating what this is or how it is used. It's not listed under directives or functions.

Upvotes: 0

Views: 30

Answers (2)

Phill
Phill

Reputation: 18796

Just adding to the comments in the previous answer:

The for attribute is used to target the input when the label and input are separate, like so:

<label for="MyId">
  My Label
</label>

<input type="radio"
       id="MyId"
       name="favorite">

If you nest the input inside the label like your example:

<label>
  My Label

  <input type="radio"
         name="favorite">
</label>

Then you don't need the for attribute, it will automatically target the input inside the label.

Upvotes: 2

user2422457
user2422457

Reputation:

It's an HTML attribute used to help browsers see the field that a label is "attached" to.

Example: Try clicking on some labels and your browser will automatically focus on the input field that it is associated with.

[PS] It has nothing to do with Angular and more of HTML and accessibility.

Upvotes: 4

Related Questions