How to use labels inside loops with AngularJS

后端 未结 3 784
陌清茗
陌清茗 2021-02-02 06:01

So I\'m inside an ng-repeat like this:

  • 相关标签:
    3条回答
    • 2021-02-02 06:32

      The correct solution is Gleno's.

      $id is guaranteed to be unique for every created scope, while $index changes with any change to the count of the underlining collection.

      You need to add the $index property(zero based) that is available on the scope in the repeater

      <li ng-repeat="x in xs">
          <form>
             <label for="UNIQUELABEL{{$index+1}}">name</label>
             <input  id="UNIQUELABEL{{$index+1}}">
             <label for="ANOTHERUNIQUELABEL{{$index+1}}">name2</label>
             <input  id="ANOTHERUNIQUELABEL{{$index+1}}">
          </form>
      </li>
      
      0 讨论(0)
    • 2021-02-02 06:33

      Since ng-repeat provides a new scope object on each iteration, I prefer using something like

      <li ng-repeat="x in xs">
          <form>
             <label for="UNIQUELABEL{{::$id}}_1">name</label>
             <input  id="UNIQUELABEL{{::$id}}_1">
             <label for="UNIQUELABEL{{::$id}}_2">name2</label>
             <input  id="UNIQUELABEL{{::$id}}_2">
          </form>
      </li>
      

      The advantage of this method is that you are guranteed not to have a duplicate selector with same id on the document. Duplicates could otherwise easily arise when routing or animating.

      0 讨论(0)
    • 2021-02-02 06:37

      For many scenarios, a better solution might be to enclose both the <input> and label text in a single <label> element. This is perfectly valid HTML, works properly in all browsers, and has the added benefit of being easy to use with hierarchical data, since you don't need to use the iterator variable:

      <li ng-repeat="x in xs">
         <label>
             Label Text
             <input type="text">
         </label>
      </li>
      
      0 讨论(0)
    提交回复
    热议问题