Skip to content

Instantly share code, notes, and snippets.

@nire0510
Last active September 19, 2017 15:28
Show Gist options
  • Save nire0510/641d9183f0972440b7a8 to your computer and use it in GitHub Desktop.
Save nire0510/641d9183f0972440b7a8 to your computer and use it in GitHub Desktop.
[AngularJS Gems] Few tips & tricks which allows you to get access to AngularJS "hidden" objects #javascript #angular
// Get access to a service. You can even execute service's methods afterwards:
angular.element('selector').injector().get('ServiceName');
// Access dom element scope:
angular.element('selector').scope();
// Access dom element isolated scope:
angular.element('selector').isolateScope();
// Access a controller:
angular.element('selector').controller();
// Injector allows you access to dependency injected components ('ng' is the umbrella module dependency for built-in services)
var $injector = angular.injector(['ng']);
//or
angular.injector(['ng']).get('$http')
(function () {
var root = angular.element(document.querySelector('[ng-app],[data-ng-app]')),
watchers = [],
watchersWithoutDuplicates = [],
f;
//Watchers deep search function:
f = function (element) {
angular.forEach(['$scope', '$isolateScope'], function (scopeProperty) {
if (element.data() && element.data().hasOwnProperty(scopeProperty)) {
angular.forEach(element.data()[scopeProperty].$$watchers, function (watcher) {
watchers.push(watcher);
});
}
});
angular.forEach(element.children(), function (childElement) {
f(angular.element(childElement));
});
};
// Execute watcher search:
f(root);
// Remove duplicate watchers:
angular.forEach(watchers, function(item) {
if(watchersWithoutDuplicates.indexOf(item) < 0) {
watchersWithoutDuplicates.push(item);
}
});
console.log('There are %d watchers in your document (%s)', watchersWithoutDuplicates.length, document.title);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment