codelord.net

Code, Angular, iOS and more by Aviv Ben-Yosef

My Angular Debugging Tips

| Comments

Yeah, I know, your code is awesome and you never write any bugs. My code does have bugs every now and then. In those cases these tips come in handy.

ng-Inspect Element

Perhaps the most useful trick is to know that once you right click on an element on screen and pick ‘inspect element’ Angular makes it very easy for you to get things going.

In the browser’s developer tools console write angular.element($0) and you now have access to all the good things:

  • Scope: angular.element($0).scope() will return the scope for the element. This is golden.
  • Controller: angular.element($0).controller() will give you the controller, doh.
  • Injector: angular.element($0).injector() returns the app’s injector, which you can then use to get access to other things (e.g. injector.get('MyService') or injector.get('$http'))

Extensions

There’s a growing number of handy extensions and snippets for Angular. Here are a few ones to try out:

  • Batarang – An official extension from Angular itself that most people love just because it shortens the previous trick from angular.element($0).scope() to $scope and the likes.
  • ng-inspector – Has similar tools to Batarang’s for looking at your app’s hierarchy, walking the scopes, etc. but works on Safari and Firefox and not just Chrome.
  • ng-stats – A little utility to show your app’s digest/watches situation, handy for spotting performance issues.

Print debugging

Print debugging is always useful, but sometimes console.logs alone are not enough. For these cases Angular provides us with a very nice little filter that even the docs say is just for debugging – the json filter.

Have some model or scope you want to see easily? Just print it: <pre>{{ someModel | json }}</pre> (Using pre means you’ll see the json properly formatted).

Bugs be gone

I hope this will help you out. If you have any other tricks I’d love to hear!

Happy debugging (well, you know, as much as possible).

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Comments