Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to debug angular code?

I'm a newbie in the Angular space. I've been having trouble debugging my code. Any methods proven more effective in debugging Angular?

like image 795
Prithvi A Avatar asked May 22 '15 17:05

Prithvi A


People also ask

How do I Debug Angular typescript?

To start a debugging session, hit the F5 key or click RUN>START DEBUGGING and a terminal will open which will begin serving your web app, and a browser window will also open. Now if you add a breakpoint to your application code, you will be able to step through the code.

How do I Debug Angular code in Chrome?

You can find the JavaScript Debugger under the sources tab of the ChromeDev Tools. As you look for bugs in your Angular code, this tool allows you to set breakpoints and inspect your code at runtime. It also gives you the capability to obtain the value of your variables at different points in time.


2 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. ngShow directive in JS is ng-show in HTML, and isOpenattribute in JS is is-open in HTML)
like image 67
Reto Avatar answered Oct 18 '22 06:10

Reto


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

like image 5
marko Avatar answered Oct 18 '22 05:10

marko