1

I have a 3rd-Party Javascript Library which is adding DOM-Elements dynamically on runtime into a div. I'm looking for a way, to detect in AngularJS (Angular 1) when this Element has been created, so I cant perform some specific actions.

<div ng-controller="myCtrl">
    <div class="thisElementWasAddedOnRuntime"></div>
</div> 

I know that there are some JS-Libraries which can detect the creation of a specific Element. But I dont want to include a whole library only for this case.

zgue
  • 3,793
  • 9
  • 34
  • 39
mkoala
  • 893
  • 1
  • 7
  • 15
  • This isn't the right way to use angular. In angular you use the model to drive/derive/create the view you don't depend on the view to do anything really, the model is the source of truth. https://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background Learn to use the directives built into the framework to achieve your goal or write custom directives. – shaunhusain Nov 30 '17 at 06:58
  • Which third party lib are you using? – lin Nov 30 '17 at 07:22
  • I know. Nevertheless I'm working on a Web Application where I'm facing this problem. – mkoala Nov 30 '17 at 07:23
  • @lin It's a custom build lib build by a vendor. – mkoala Nov 30 '17 at 07:24
  • Jap, I went cleaning up to code and did it your way. Thanks! – mkoala Dec 07 '17 at 06:57

2 Answers2

1

You need to create a custom directive to make it work right. Please take a look at this simple fiddle demo. You are able to access the element inside your directive link function. There you should bind your third party lib on your element. Directives are markers on a DOM element that tell AngularJS's HTML compiler to attach a specified behavior to that DOM element. You could also take a look at the directives documentation.

View

<div ng-controller="MyCtrl">
  <div my-directive></div>
</div>

AngularJS application:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {});

myApp.directive('myDirective', function() {
  return {
    restrit: 'A',
    link: function(scope, element, attrs) {
        // use element here to bind your lib
        console.log(element);
    }
  }
});
lin
  • 17,956
  • 4
  • 59
  • 83
0

Right way to observer dom change in angular is directive's link .

link:function(scope,ele,attr){
        if (MutationObserver) {
            observer = new MutationObserver(function (mutations) {
               console.log('changed');
            });

            observer.observe(ele[0], {
                childList: true,
                subtree: true
            });
        } else {
            ele[0].addEventListener('DOMSubtreeModified', function (evt) {
               console.log('changed');
            }, false);
        }
      }

TRY THIS : http://jsbin.com/pizizatuhi/1/edit?html,js,console,output