fbpx Skip to content

Aquent | DEV6

AngularJS and the console

Written by: Alain Thibodeau

Ever find the need to change your application’s state directly in the browser to test something? Perhaps your application has two states based on a Boolean set somewhere and you want to test these states. It is possible to achieve this in the console. In fact, there are several ways to achieve this. The idea is to get a reference to the scope, then you can access any properties or functions from there.

Here are some examples that you can directly type in the console.

Using any variation of query selectors

CSS classes:

var elem = angular.element(document.querySelector('.my-class'));
elem.scope().myProperty = true;
elem.scope().$apply();

Finding first ng-controller:

var elem = angular.element(document.querySelector('[ng-controller]'));
elem.scope().myProperty = true;
elem.scope().$apply();

Templates:
If you declared your controller in the template like this:

You could access it directly.

var elem = angular.element(document.querySelector('[ng-controller=MyController]'));
elem.scope().myProperty = true;
elem.scope().$apply();

Using jQuery:

$('#myElement').scope().myProperty = true;
$('#myElement').scope().$apply();

Using Batarang

If you have Batarang, select the element you need the scope from and then just type $scope in the console. More information can be found here.

Injector

You can also get a reference to any injectors that the targeted controller is injecting like this:

var elem, injector, config;
elem = angular.element(document.querySelector('[ng-controller]'));

injector = elem.injector();
myService = injector.get('myInjectedService');
myService.doSomething();
elem.scope().$apply();

As you can see, it is quite easy to access the scope or injectors to update properties or invoke methods on them. This can be useful for testing specific behaviour or state changes in your application at run time.

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

view course details