Skip to content

Instantly share code, notes, and snippets.

@cristoferdomingues
Created April 13, 2017 19:27
Show Gist options
  • Save cristoferdomingues/e3b5a0028b298454f9f8b49dc2fa311d to your computer and use it in GitHub Desktop.
Save cristoferdomingues/e3b5a0028b298454f9f8b49dc2fa311d to your computer and use it in GitHub Desktop.
Angular DOM Mutation Observer
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.2.4" data-semver="1.2.4" src="http://code.angularjs.org/1.2.4/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<h1>MutationObserver with angular</h1>
<button class="btn-success" ng-click="addChildToDirective()">Add Child</button><small>Look in your console ;)</small>
<some-directive></some-directive>
</body>
</html>
// Code goes here
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.children = [{id: '1', name: '1'}, {id: '2', name: '2'}];
$rootScope.addChildToDirective = function() {
$rootScope.children.push({id: ''+$rootScope.children.length, name: ''+$rootScope.children.length});
}
})
.directive('someDirective', function() {
return {
restrict: 'E',
template: '<ul>'+
' <li ng-repeat="child in children">'+
' <span ng-bind="child.id"></span>'+
' <span ng-bind="child.name"></span>'+
' </li>'+
'</ul>',
link: function (scope, element, attr) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// you get notified about added DOM elements here
// check mutation.type if it was an insertion
console.log(mutation.target.nodeName, mutation.type, mutation);
});
});
var config = {childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true};
observer.observe(element[0], config);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment