【问题标题】:Giving unique id to each item in `ng-repeat` for DOM manipulations为 `ng-repeat` 中的每个项目赋予唯一的 id 以进行 DOM 操作
【发布时间】:2015-06-04 16:03:18
【问题描述】:
.div(ng-repeat='item in items') 
   button(id='ID{{$index}}') No Hi

button(id='anotherID1') Hi

在相关的 Angular 指令中

$('#ID1').on('click', function() {alert('hi');});  // does not work 

$('#anotherID1').on('click', function() {alert('hi');}); // works

我正在执行 DOM 操作,我需要 ng-repeat 元素的唯一 ID。还请建议是否也可以以任何其他方式执行 DOM 操作。

编辑:@tymeJV:-

 style.
  .ques {
    height: 50px;
    overflow:hidden;
  }



<div ng-repeat='item in items'>
    <div class='ques'> {{item.ques}}
    </div>
    <button id='ID{{$index}}'> No Hi </button>
</div>

// 指令代码:- 增加&lt;div class = 'ques'&gt;的高度

【问题讨论】:

  • 只是想知道:你的模板引擎是什么:jade?​​span>
  • 最终生成的html是什么。 id 属性在其中看起来如何?
  • 请使用指令进行 DOM 操作! jQuery 风格的点击处理程序不是很 Angular-y。
  • @Chandermani angular 无法识别通过ID{{$index}} 生成的ID1,因此前一条语句无效
  • @tymeJV 我正在使用指令。上面的代码只是指令的一部分。但是里面有jQuery。如果你可以建议替代代码。请做。

标签: angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

首先,如果您使用 Angular,建议您坚持使用标准的 Angular 监听器指令,而不是恢复为 jQuery。因此,不要使用 jQuery 的 on,而是在您希望 Angular 绑定侦听器的 HTML 事件上使用 ng-click 属性。

例如:

HTML

<button ng-click="doStuff()">
</button>

控制器

$scope.doStuff = function () {
    //perform action
};

为了为ng-repeat创建的每个元素存储一个唯一的ID,如何在doStuff调用中添加一个ID为ng-click="doStuff(item.ID)"的参数并在$scope.doStuff方法中访问它。

【讨论】:

  • 对于 DOM 操作,建议使用指令而不是控制器。 $scope.doStuff = function () { //执行操作 };是控制器代码的一部分,而我正试图通过指令来完成它。
【解决方案2】:

id={{'flowchartWindow'+$index}} 这对我有用

【讨论】:

    【解决方案3】:

    试试 按钮(id={{'ID'+$index}})

    【讨论】:

      【解决方案4】:

      为我工作。

      http://plnkr.co/edit/llSc8o?p=preview

      所以我怀疑 sushain97 是对的,问题不在于您使用 angular 的方式(事件绑定除外)。

      【讨论】:

        【解决方案5】:

        对于动态分配的 id。 $('#ID1').on('click', function() {alert('hi');}); 的语法有点改变为

        $('#YourWrapperID').on('click','#id1' , function(){
            alert('hi');
        });
        

        完美运行!

        【讨论】:

          猜你喜欢
          • 2017-12-15
          • 2015-10-12
          • 2015-06-19
          • 2015-07-07
          • 2017-09-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多