Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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);
             }
         });
     }
});

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
388 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's a bad idea, but I'll humor you.

So as I've stated in my comments above, it's a bad idea to do what you're trying to do. That said, if you still want to go this way, you can $watch just about anything by passing a function in as the first parameter.

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.
});

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

  • when a value changes in an input
  • when the selection changes on a dropdown
  • when an attribute changes in any element in the html.
  • etc.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...