Natan
Natan

Reputation: 4958

How to access the component controller from browser console?

In angular 1.x, when using ng-controller, one can access the controller instance from the browser console by inspecting an element and calling angular.element($0).controller().

This doesn't work with components declared as:

angular.module('foo').component('bar', {
    controller: class {

    }  
});

Is there any other way to access the component's controller instance from the console?

Upvotes: 3

Views: 2712

Answers (2)

Estus Flask
Estus Flask

Reputation: 222750

As the manual states,

controller(name) - retrieves the controller of the current element or its parent. By default retrieves controller associated with the ngController directive. If name is provided as camelCase directive name, then the controller for this directive will be retrieved (e.g. 'ngModel').

It is angular.element($0).controller('bar').

For a component this may be narrowed down to

 angular.element($0).controller(
   $0.tagName.toLowerCase().replace(/-([a-z])/g, (_, c) => c.toUpperCase()))
 );

one-liner.

Upvotes: 1

Natan
Natan

Reputation: 4958

It seems the closest we get to access the component controller is:

angular.element($0).scope().$ctrl

Upvotes: 4

Related Questions