Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:53
Show Gist options
  • Save dotproto/05869087b12dc9ebd386d3914e923712 to your computer and use it in GitHub Desktop.
Save dotproto/05869087b12dc9ebd386d3914e923712 to your computer and use it in GitHub Desktop.
Utilities for working with and debugging Angular.js 1.x apps (ES6)
(function exposeNgUtil(target = window) {
if (!angular) {
console.error(`ERROR: ng-util cannot initialize because "angular" was not found!`);
return null;
}
getScope = el => angular.element( (el || document.getElementsByClassName('ng-scope')[0]) )
let ngUtils = {
// Use Angular.js' DI system to retrieve a provider.
//
// @param {String} dep The name of the provider to retrieve
// @returns An Angular.js Provider (e.g. '$log' or '$http')
inject: dep => getScope().injector().get(dep),
// Get the isolate scope associated with a given element. If the caller
// does not provide a target element, the function will fall back to the
// first element with 'ng-scope' on the page.
//
// @param el The DOM element that you want to retireve the isolate scope of
// @returns The isolate scope associated for that element
isolate: el => getScope(el).isolateScope(),
// Get the scope associated with a given element. If the caller does not
// provide a target element, the function will fall back to the first
// element with 'ng-scope' on the page.
//
// @param el The DOM element that you want to retireve the scope of
// @returns Anagular.js scope for the specified element.
scope: el => getScope(el).scope(),
// Retrieves a function's parameter list using Angular's internal
// annotation utilities.
//
// $$annotate exists in 1.5 -- I don't know about other versions
args: fn => angular.injector.$$annotate(fn),
};
if (target === window) window.ngUtils = ngUtils
else Object.assign(target, ngUtils)
})()
// Check to make sure that everything's working
ngUtils.inject('$log').info(`ng-utils loaded!`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment