【问题标题】:What happens when removing an object used by a ngRepeat in AngularJS?在 AngularJS 中删除 ngRepeat 使用的对象时会发生什么?
【发布时间】:2013-08-26 15:27:00
【问题描述】:

编辑:jsFiddle 此处为示例。

我有一个ngRepeat,它生成包含iframes 的指令。

div(ng-repeat='element in elements')
    ng-switch(on="element.type") 
        a-directive(ng-switch-when="something")
        another-directive(ng-switch-when="somethingElse")

现在,在指令中,我在某些事件之后将内容加载到 iframe 中,方法是:

$iframe[0].contentWindow.d_contents = "html"
$iframe[0].src = 'javascript:window["d_contents"]'

一切都很好。

当我从模型中(在控制器中)删除这些元素之一时:

elements.remove(object) //using sugarjs, that's not the issue, same behaviour with splice

UI 会相应更新,即元素消失。

问题

这按预期工作:

elements.push(ele1)
elements.push(ele2)

.. init iframes inside ele1 and ele2 with content ..

elements.remove(ele2) 

结果:ele2 从 UI 中消失,ele1 仍然存在并加载了 iframe

这不是:

elements.push(ele1)
elements.push(ele2)

.. init iframes inside ele1 and ele2 with content ..

elements.remove(ele1) 

结果:ele1 从 UI 中消失,ele2 仍然存在 iframe,但 iframe 内容恢复为空,iframe.load() 被解雇。

这里发生了什么?为什么我的 iframe 会被重置?

【问题讨论】:

  • 有用信息:当您有 3 个元素并删除第二个元素时,只会重新加载第三个 iframe。
  • 是的,似乎删除一个元素会将其他元素移回 1 个位置,并且指令中的某些内容发生了变化..

标签: iframe angularjs angularjs-directive ng-repeat


【解决方案1】:

您需要在 load() 中添加加载逻辑,以便在 DOM 更改时重新加载内容。

var linkfn = function (scope, element, attrs) {
    init(function () {
        var $iframe = element.find("iframe")

        var refresh = function () {
            var doc = $iframe[0].contentWindow.document;
            doc.open();
            doc.write(scope.ele.source);
            doc.close();
        }

        $iframe.load(function () {
            console.log(scope.ele.id + ": loaded ");

            //refreshing
            refresh();
        });

        //initial loading
        refresh()
    })
}

这种情况需要使用doc.write(),否则会出现递归循环错误。

DEMO

【讨论】:

  • 谢谢,但这不是一个解决方案,它只是一个 hack(我这样做了......为了避免循环,只检查正文内容) - 问题是它不应该在我重新加载内容时删除另一个元素。
  • @fusio 为什么不是解决方案?为什么它是一个黑客?为什么删除元素时不应该重新加载内容?你真的了解 Angular 的工作原理吗?每当您从数据源中添加或删除时,AnguarJS 都会绑定来自数据源的 entire 数据。
  • 哦,见鬼。数据源是指范围?每次我修改某些内容时,它都会重新加载整个范围?还是数据源是数组?不知道。
  • 你能澄清一下吗?我不明白为什么删除一个数组项会刷新以下所有项(但不是数组中的先前项) - 没有任何通知:|
猜你喜欢
  • 2022-06-27
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多