我创建了一个小型实用程序服务
这是代码
在GenericService.js
我们有这个
angular.module('GenericServiceModule', [])
.factory('$utilsService', function () {
var utilService = {};
utilService.observeDomChange = function (domElement, doThisOnChange, observationOptions) {
var defaultOptions = {
// attributes: true, // attribute changes will be observed | on add/remove/change attributes
// attributeOldValue: true, // will show oldValue of attribute | on add/remove/change attributes | default: null
// we need this because in .find() sizzle modifies id temporarily, https://github.com/jquery/jquery/issues/2620
//attributeFilter: ['style'], // filter for attributes | array of attributes that should be observed, in this case only style
// characterData: true, // data changes will be observed | on add/remove/change characterData
// characterDataOldValue: true, // will show OldValue of characterData | on add/remove/change characterData | default: null
childList: true, // target childs will be observed | on add/remove
subtree: true // target childs will be observed | on attributes/characterData changes if they observed on target
};
var options = observationOptions || defaultOptions;
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observer = new MutationObserver(function anElementIWatchChanged(mutations) {
doThisOnChange();
});
// removing the dom element won't be triggered
observer.observe(domElement, options);
};
return utilService;
});
并且您可以像使用它一样简单地使用它
$utilsService.observeDomChange($element[0], doSomething());
这是一个用法示例
angular.module(
...
.directive('myCustomDirective', function ($utilsService) {
return {
restrict: 'A',
//...
controller: function ($scope, $element) {
//...
$scope.$on('$viewContentLoaded', function (event, viewName) {
$utilsService.observeDomChange($element[0], doSomething());
}
}
}
}