1

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

<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 但没有成功将这对输入/标签放在一起,我的意思是输入+标签的顺序与本示例中的相同。

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

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

这种尝试

.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")

什么都不给,

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

J。

4

2 回答 2

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

于 2013-06-03T03:37:42.633 回答
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]。)

于 2013-06-03T02:41:24.857 回答