【问题标题】:Inject a unique DOM element in at a specific position in a ng-repeat using Angular使用 Angular 在 ng-repeat 中的特定位置注入一个唯一的 DOM 元素
【发布时间】:2015-06-08 22:42:18
【问题描述】:

我有一个复杂的网格指令,它绑定到一个长列表模型对象。对于我的一个应用程序,我有一个列表,我需要在其中注入所选行中的指令。代码类似于

<div id='grid-like' myComplexDirective style='display:none'></div>

<div ng-repeat='item in items'>
    <div class="data-row">
        <!-- stuff with item object -->
        <button ng-click='insertControl()'></button>
    </div>
    <!-- Here is where i'd like to inject the grid-like control and show/hide when button is clicked -->
</div>

我需要这样做以避免复杂组件的多个实例(现在,它包含在每一行中,根据范围的切换值显示/隐藏),因为它很重并且使应用程序缓慢。 我尝试使用 insertControl 方法中的 appendTo 方法移动 jquery 中的元素。不幸的是,一旦我改变视图,它就不起作用了。经过一番研究,我发现我需要使用 Angular 指令与嵌入或使用 $compile。

执行跨视图的 jquery appendTo 的角度方式是什么?

【问题讨论】:

  • 不确定我是否了解您的需求,但您可以使用push() 方法吗?例如:$scope.items.push(newItem);
  • 我不是想在模型中插入更多的项目,而是在 DOM 中只有一个复杂元素的实例,并将其动态地放置在另一个给定的 DOM 元素中。

标签: jquery angularjs appendto transclusion


【解决方案1】:

使用 ngIf。

来自 Angular 文档:

ngIf 指令删除或重新创建 DOM 树的一部分 基于一个{表达式}。如果分配给 ngIf 的表达式计算 为 false 值,则从 DOM 中删除该元素,否则为 元素的克隆被重新插入到 DOM 中。

<div ng-repeat='item in items'>
    <div class="data-row">
        <!-- stuff with item object -->
        <button ng-click='item.insertControl=true'></button>
    </div>
    <!-- Here is where i'd like to inject the grid-like control and show/hide when button is clicked -->
    <div ng-if="item.insertControl">
         ... some complex control ...
    </div>
</div>

如果您担心性能问题,请改用 ngShow。 DOM 操作很昂贵,ngShow 避免了这种情况。

【讨论】:

  • 感谢您的回答。现在,我用 ng-show 就是这样做的,但感觉很慢。我认为 Angular 将复杂元素添加到每一行的 DOM,即使条件评估为假(我可能错了)。由于我不太明白的原因,ng-if 不起作用(但 ng-show 起作用)......
  • 数百个不应导致任何性能问题或迟缓行为。您是否在指令中使用 jquery 选择器?我怀疑不是摘要循环导致问题的原因
  • 是的,它确实使用 jquery。虽然在 ng-repeat 之外加载时它非常庞大......
  • 感谢您花时间回答。我会接受你的回答。
猜你喜欢
  • 1970-01-01
  • 2013-03-22
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2013-03-03
相关资源
最近更新 更多