So if you want to learn AngularJS, of course you need to know how to setup a AngularJS project in Visual Studio. There are couple of Visual Studio templates available like AngularJS SPA Template, which you can download and use with Visual Studio. But in this post, let’s see how you can create one from the scratch.
Let’s power up Visual Studio and create an Empty ASP.NET project (Please note I am using Visual Studio 2013).
|Adding AngularJS through Nuget|
Alternatively, you can use Package Manage Console to install AngularJS. Once it gets installed, you can see a new folder named “Scripts” added to the project which contains all the AngularJS files needed to start the project off with.
Now inside my project, let’s create a folder named “App”. The “App” folder is going to be the one folder which will contain all our UI components. Inside “App” folder, let’s create two folders named “controllers” and “views”. “controllers” folder will contain all the AngularJS controllers and “views” folder will contain all the templates (html pages). All the templates will be rendered inside one html page. Let’s create that main html page named “Index.html” inside “App” folder.
|Add new HTML page|
Here in the “app.js”, there are some couple of key components. Since our application is Single Page Application, we don’t want any page refreshes. Here we are using AngularJS routing capabilities by injecting $routeProvider in AngularJS. There I am saying when the Url is “/” load the “views/home.html” which is bound to “homeController”. When the Url is “/about”, same way load the “views/about.html” which is bound to “aboutController”. There is also a controller defined “mainController”.
Now let’s create the views.
Now let’s modify the “Index.html” integrating all together and defining which displays where.
Here first in <html>, I have mentioned ng-app directive, which powers up the AngularJS. Then in the <head></head> section, I have included all the necessary scripts. Then in <body></body> section, first I have added a <div> which will contain links for navigation. For linking to pages, # (hash tag) is used. We don’t want the browser to think we are actually travelling to “home.html” or “about.html”.
Then defined a <div> which is bound to “mainController”. There first I am displaying the value in $scope.message in “mainController”. Then I have a ng-view which defines a angular template and the templates will be injected inside ng-view.
So that’s it. When we run the project I am getting the following output.
Here note the Url is “/”
So hope you found this interesting. I am uploading the full sample to OneDrive. Enjoy!.