Angular指令ng-repeat生成一对元素input + span

时间:2013-06-02 20:30:54

标签: angularjs directive ng-repeat

这是我的请求,使用指令我尝试在上面生成这个结构:

<div class='myClass'>
    <input id="id0" name="name0" type="radio" checked>
    <label for="id0" ng-click="myAction('0')"> 0</label>

    <input id="id1" name="name1" type="radio">
    <label for="id1" ng-click="myAction('1')"> 1</label>

    <input id="id2" name="name2" type="radio">
    <label for="id2" ng-click="myAction('2')"> 2</label>

    ...3,4,5...

    span(class="endSpanClass")

不是很简单:

我尝试过多种方式使用指令,ng-repeat但没有成功将这对输入/标签放在一起,我的意思是输入+标签的顺序与本例中的顺序相同。

然后在第一个元素上,我希望获得“检查”属性。

最后一个跨度也必须设置在最后。

那种尝试

.directive('myDirective', ['$timeout', function(timeout) {
    return {
      restrict: 'A',
      controller: 'MyController',
      scope: {myList: '='},
      template: '<input id="id0" name="view" type="radio">' +
      '<label for="id0" ng-click="myAction(\'day\'> 0 </label>',
      transclude: false,                    
      replace: true,
      link: function($scope, element, attr, ctrl) {


      }
    };
}])

我的指令叫

div(class='myClass')
    input(my-directive, my-list='list', ng-repeat="item in list", id="0", name="name0", type="radio")

什么都不给,

如果你能提供帮助并给我一些建议,谢谢。

学家

2 个答案:

答案 0 :(得分:1)

以下是我要做的事情:

<label ng-repeat="name in names">
  <input name="{{name}}" type="radio"
   ng-checked="$index==0"
   ng-click="myAction($index)"/>
  {{$index}}
</label>
  1. 通过label包装表单控件,这将简化代码 还明确指出什么标签控制什么控制。 (只是一种标准的html技术。)

  2. 使用ng-checked来控制已检查状态。

  3. 我会避免使用这个短代码的指令,除非 它在很多地方被多次使用。

  4. 如果使用指令,则模板必须具有单个根元素。 (所以你实际上可以采用上面的技术[1]。)

答案 1 :(得分:1)

这是一个简单的指令定义:

app.directive('myDirective', ['$timeout', function(timeout) {
    return {
      restrict: 'E',      
      scope: {id: '='},
      template: '<div><input id="id{{id}}" name="view" type="radio">' +
      '<label for="id{{id}}" ng-click="myAction(\'{{id}}\')">{{id}}</label></div>',      
      replace: true
    };
}])

除了一个工作示例:http://plnkr.co/edit/spQRs5xs43P1FOX7YQzH?p=preview