Developing AngularJS applications is fun. However, debugging certain aspects of your application might not be as straight forward as we might think. Here are few tricks we can use to inspect the AngularJS application from the javascript console of your browser.

In webkit based borwser if we inspect the element, then that element can be accessed using $0.
For example sake lets just take the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Scope Apply Example</title>
    <script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js'></script>
    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('FirstController', function($scope) {
            $scope.person = {
                fname: "James",
                lname: "Bond"
            };
    </script>
</head>
<body>
    <div ng-controller="FirstController">
        First Name:
        <input type="text" ng-model="person.fname" name="fname" placeholder="Enter First Name" />
        <br/>Last Name:
        <input type="text" ng-model="person.lname" name="lname" placeholder="Enter Last Name" />
        <br/>Hello {{person.fname}} {{person.lname}} !!
        <br/>{{person}}
    </div>
</body>
</html>

1. In you browser console:
The document.body you see below is just a dom node selector, you can use any of the techniques that you already have (Ex: document.querySelector(‘.yourclass’) or jquery way of accessing elements, $0 etc). The thing to note is we need to provide a dom node reference to angular.element

var a = angular.element(document.body).children();
a.scope();

This would give the object hierarchy, you can see the person model as well.
now we can access it like

a.scope().person.fname='Thames'
a.scope().$apply();

2. You can access any other services through the injector method:

var log = angular.element($0).injector().get('$log');
log.info('an info');

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>