如何观察 DOM 的变化 AngularJS [英] How to watch the DOM for changes AngularJS

查看:22
本文介绍了如何观察 DOM 的变化 AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个愚蠢的问题,但我需要知道如何查看页面的整个 DOM 并在它发生变化时重新编译它.本质上,这是 AngularJS 默认使用数据绑定所做的事情,但我需要在 DOM 中的任何内容发生更改时发生这种情况,而不仅仅是绑定.原因是因为我有一个完全用 HTML、Javascript 和 PHP 构建的应用程序.这是一个单页应用程序,它有一个主页面,并将 PHP 注入到该页面内的 DIV 包装器中.

This may seem like a silly question but I need to know how to watch the entire DOM of a page and recompile it any time it changes. Essentially this is what AngularJS does by default by use of databindings, but I need this to happen anytime anything in the DOM is changed, not just bindings. The reason why is because I have an app that is built entirely in HTML, Javascript and PHP. It's a single page application, it has a main page and injects PHP into a DIV wrapper within that page.

我想对其进行一些修改,但想让我的代码与原始代码完全分开.为此,我需要能够在注入具有自己的 DOM 结构的新 PHP 文件时重新编译 DOM.到目前为止,我所拥有的似乎不起作用.

I want to make some modifications to it but want to keep my code completely separate from the original code. To do this I need to be able to recompile the DOM anytime a new PHP file with it's own DOM structure is injected. What I have so far does not appear to be working.

app.directive("watch", function () {
    return function (scope, element, attr) {
        scope.$watch("watch", function(oldValue, newValue) {
            if(newValue) {
                console.log("there is a new value");
                console.log("the new value is " + newValue);
             }
         });
     }
});

我在 <body> 标签中添加了 watch 属性,但它似乎不起作用,当 dom 更改时,没有记录任何内容.最终我想用 $compile 替换 console.log,但我首先需要让手表工作.有人可以指出我做错了什么吗?

I add the watch attribute the the <body> tag but it doesn't seem to work, when the dom is changed nothing gets logged. Ultimately I'd like to replace the console.log with $compile, but I first need to get the watch to work. Can someone point me to what I'm doing wrong?

推荐答案

这是个坏主意,但我会逗你开心.

所以正如我在上面的评论中所说的那样,做你想做的事情是一个坏主意.也就是说,如果您仍然想这样做,您可以通过将函数作为第一个参数传入来$watch 进行任何操作.

下面的代码将检查 标签内的 HTML 是否已更改.请注意,这是一个可怕的想法.

The code below will check to see if the HTML inside the <body> tag has changed. Please note, that this is a HORRIBLE idea.

$scope.$watch(function () {
   return document.body.innerHTML;
}, function(val) {
   //TODO: write code here, slit wrists, etc. etc.
});

上面的监视将在 HTML 更改中的任何任何触发.

The watch above will fire anytime ANYTHING in the HTML changes.

  • 当输入中的值发生变化时
  • 当下拉列表中的选择发生变化时
  • 当 html 中任何元素的属性发生变化时.

附加信息: 就目前而言,在很多浏览器中,并没有真正好的方法来监控已加载的新 DOM 元素.最好的方法仍然是在添加新 DOM 元素的那一刻触发.

Additional Info: As of right now, in a whole lot of browsers, there's not really a good way to monitor for new DOM elements which have been loaded. The best way is still to trigger something at the moment the new DOM elements were added.

这篇关于如何观察 DOM 的变化 AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆