Skip to content

Instantly share code, notes, and snippets.

@auxcoder
Last active August 21, 2017 17:23
Show Gist options
  • Save auxcoder/15dc60645cfdc9c329efdd096061dd08 to your computer and use it in GitHub Desktop.
Save auxcoder/15dc60645cfdc9c329efdd096061dd08 to your computer and use it in GitHub Desktop.
Access to Angular from console to debug

Access to Angular from console to debug

We can get whatever service we like and then call an specific method.

var serviceName = angular.element(document.body).injector().get('serviceName');
serviceName.someMethod();

Example: get info in cookies.

var cookies = angular.element(document.body).injector().get('$cookies');
cookies.getObject('SOMEKEY');

Pick an element in the HTML panel of the developer tools and type this in the console.

var a = angular.element($0).scope();

We can call any method in that controller.

a.methodInController();

You can also target the scope by element ID, like so:

var a = angular.element(document.getElementById('yourElementId')).scope()

Access and change variable in scope:

angular.element(myDomElement).scope().myVar = 5;
angular.element(myDomElement).scope().myArray.push({item: 'value'});

After you make changes to your model, you'll need to apply the changes to the DOM by calling:

var scope = angular.element(myDomElement).scope();
scope.$apply();

Access to $rooScope

var $body = angular.element(document.body);
var $rootScope = $body.injector().get('$rootScope');
console.log($rootScope);

jQuery Lite

If you load jQuery before AngularJS, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with Find your scope by controller name, do this:

angular.element('[ng-controller=ctrl]').scope()

Of a button

angular.element('button:eq(1)').scope()

jQuery

$('#elementId').scope();
$('#elementId').scope().$apply();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment