< Blog

AngularJS debugging tips

angularjsdebugging

Accessing $scope of a component on the DOM

When you select an element in the Dev Tools, a variable is created called $0 which is a reference to the element selected. You can then get the $scope of that selected element by running the following command:

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

Which allows you to access the scope & modify the scope (i.e. $scope.vm.customerName = "Steve!";). Don't forget you scope.$apply() if you do edit anything so that angular will try to reevaluate the value & update the DOM

The above command can also be run with selectors:

var scope = angular.element("#my-component").scope()

If you install the Batarang Chrome extension, a $scope variable will always be automatically assigned based on the element you select in the Dev Tools so you don't need to run the above snippet to set a $scope variable.

You can also access parent scopes (using $scope.$parent) or the rootScope (using $scope.$root)

Accessing instances of a service

You can easily extract any service that has been injected in to your AngularJs application with the following snippet:

var myService = angular.element(document.body).injector().get('myService');
myService.doSomethingAwesome("yay!");

Dumping objects

In some cases you may want to debug / develop and need to access data in your scope without having to constantly run console commands. The below will dump an object from $scope into the DOM and format it as JSON.

<pre>{{ vm.someModel | json }}</pre>

Common AngularJS Issues

Objects on the scope sometimes don't update (or update with a delay)

Sometimes when running code in a non angular context, angular doesn't know what has happened or changed so may not process the changes straight away. The most popular case for needing this is in 3rd party libraries that don't know about angular or don't have an angular version / wrapper around the original library.

A common example of this is setTimeout, which will schedule the page to run a function outside of angular

vm.name = null;

setTimeout(() => {
    vm.name = "Steve";
    vm.showFireworks();
    $scope.$apply(); // Force angular to run the digest cycle
});
Enjoy my content? Want to buy me some snacks and support this hungry developer?
Buy Me A Coffee
< Blog