Angular JS Tip – 4 (Webstorm and ng-include)

One of the benefit of ng-include is to stip the HTML template code out of main code and keep is as separate code and just include them in the screens where you want them. Going with the previous example, on user select a student from a list box, I want to display the user information in details. I stripped the HTML code which display the student details and put it in a HTML file and called it ‘studentDetails.html’. Now here is the important part, if you want to use the html file in the angular, it is very important that, you not only surround the string value with “” but also with ”, by having both the values in the angular, tells angular, to treat the value as string constants and do not evaluate it as expression. With that, our studentdetail.html as follows;

<table>
<tr><td>ID</td><td>{{selectedItem.id}}</td></tr>
<tr><td>Name</td><td>{{selectedItem.name}}</td></tr>
<tr><td>Age</td><td>{{selectedItem.age}}</td></tr>
<tr><td>Country</td><td>{{selectedItem.country}}</td></tr>
</table>

index html file not have nothing but ng-include like the following

<div ng-include=”‘studentDetails.html’”></div>

*** Very important point here is, the constant value is surround with double quote and also single quote. ***

If you are using webstorm and created this app as basic empty web app and try to run this, you will get the following run time error

XMLHttpRequest cannot load file:///Users/user/WebstormProjects/javascript/angulartemplatesdemo/studentDetails.html. Origin null is not allowed by Access-Control-Allow-Origin. index.html:0

A quick search showed me why running in file mode will not work. So to make it work, I simply point to local host (http://localhost:63342/angulartemplatesdemo/index.html)  as specified in the previous blog and ran and start working.

So two things

  1. To use a string in ng-include, make sure you surround it will single and double quotes.
  2. When using ng-include and testing with webstorm make sure, you run it with build in server other wise you will get run time error.