I'm a newbie in the Angular space. I've been having trouble debugging my code. Any methods proven more effective in debugging Angular?
-
I usually use FireFox (FIreBug) because I can inspect the Angular scope. For all other js testing, I use Chrome DevToolsOwen– Owen2015-05-22 17:49:59 +00:00Commented May 22, 2015 at 17:49
-
having what trouble? Question is pretty vaguecharlietfl– charlietfl2015-05-22 18:08:44 +00:00Commented May 22, 2015 at 18:08
-
Write unit and integration testsAJcodez– AJcodez2015-05-22 18:34:43 +00:00Commented May 22, 2015 at 18:34
4 Answers
open the developer console in the chrome browser, this allows you to:
- set breakpoints and see whats going on in your code
- use the console in the developer tools while you are waiting in breakpoints to execute some code or check the contents of variables
- use the "select element" tool to select any HTML element, then in the console type "$scope" to see what's on the $scope of this element.
general tipps:
- use some console.log statment like "running ControllerXYZ now" so you see, when your controllers are executed or when you are transitioning between states.
- When using ui-router I find it extremly important to add a console.log statement into $stateChangeStart, $stateChangeSuccess and $stateChangeError event handlers, that shows you when you transition between states or when errors happen on state transitions, without that I am blind...
- adding some
{{anImportantVariable | json}}into html often is enough to debug stuff.
and the most important: if everything looks ok, and it still does not work, the problem is in 99%:
- either a scoping issue (see here: Why do I need $parent to enable the function in ng-click when using ion-scroll?)
- or a spelling mistake and a directive is not found (often because of the CamelCase in JS to dash-case in HTML: e.g.
ngShowdirective in JS isng-showin HTML, andisOpenattribute in JS isis-openin HTML)
1 Comment
When it comes to inspecting the state: even though I always (irony) write unit tests for each and every conditional in my code (so I normally don't need to debug stuff) this is so far my favourite technique:
<pre ng-show='mymodel.debugPlz'>{{ mymodel.something | json }}</pre>
Simple example : fiddle
Comments
Chrome DevTools usually get the job done pretty well. You can insert a debugger; statement anywhere in the code and if Chrome DevTools are open, the code will stop there and you can further add breakpoint and traverse lines one by one. Other than that, there are a few extensions you can use by just searching for Angular in the Chrome Webstore. These usually help with inspecting $scope
2 Comments
what about using AngularJS Batarang chrome extention
it gives you a nice overview of the current scope within the selected element
as you see in the screenshot there is a new scope tab
