Your First Angular Project in Visual Studio

angular-visual-studio

Today is the day. You have been hearing about Angular for a long time now. You have listened to the podcasts, you’ve watched the videos, and you have followed the pre-canned tutorials. Now you are creating your own project. Maybe you have an application idea or you plan to work your way through the documentation. You open up Visual Studio and pause. Which type of project template should you use? What type of back-end should you setup? So many questions.

This post looks to simplify the process and walks through a basic project structure in Visual Studio designed for quick setup and a solid foundation for separation of concerns. The structure aims for simplicity yet some of the recommendations may not be intuitive for the average ASP.NET developer. Angular is a client-side framework and therefore much of the ceremony performed to use ASP.NET for server-side development is unnecessary.

This walk through is for Visual Studio 2013. If you don’t have it, download the community edition (it’s FREE) and get the latest updates. Also install the Web Essentials extension to get the latest web development tooling for Visual Studio. If you have seen Visual Studio 2015, it introduces a new project structure that aids with client-side development. Even though this project structure is aimed at Visual Studio 2013, it should make it is easy to migrate to Visual Studio 2015 when the time comes.

Also, this post doesn’t cover build tools for bundling, minification, and testing even though Visual Studio supports these scenarios. Look for posts on these topics in the future.

Choosing the Project Template

This walkthrough uses a web application project as opposed to a web site project. This is part personal preference and part pragmatism. If you are significantly more comfortable with web site projects, go head and use them. It doesn’t make a significant difference for the purpose of this post.

Using a web application project is not straightforward, however. The tricky part is how the default templates setup things you don’t need – mainly everything specific to ASP.NET.

In the world of client-side frameworks, there is a much cleaner separation of client and server. There is generally no need to create .aspx or .cshtml files in order to render views on the server. Much of the rendering logic in these files can be done in Angular with static HTML files. There may be reasons to use server-rendered views for specific scenarios but start out considering that you don’t need server-rendered views.

“But what about data?” you say. Start out by using static .json files on the file system or hard code collections in your JavaScript. If you need to persist data, there are various in-browser technologies to save what you have done. Eventually yes, you will need to create a back-end but not for starting a basic Angular project.

Now it’s time to create the project. Go ahead and create an ASP.NET Web Application project.

create-first-vs-project

Press OK and this brings you to the dialog where you choose a template and select the features for your application. Choose the Empty template and uncheck all of the ASP.NET features.

create-empty-vs-project

Press OK to create the project. You see the project is indeed empty.

empty-structure

If you press F5 to run the project, you will get a 403 Forbidden error from IIS because there is nothing for you to access.

There is no need for server-side controllers, views or routes at this time. To start, add an index.html file to the root of your project, type Hello World in the body, hit F5 and you will see your friendly message in the browser.

Adding Angular

In order to write an Angular app, you need to reference the Angular JavaScript library. You can go to the Angular website and download it or reference it from the CDN (content delivery network). However, Visual Studio has the NuGet package manager to easily download the scripts and add it to your solution.

Note: in Visual Studio 2015, client-side dependencies will typically be loaded via client-side package managers as opposed to NuGet.

To load the Angular scripts from NuGet, right click on the solution and select ‘Manage NuGet Packages for Solution…’ from the dropdown. This displays the NuGet dialog. Search for “angularjs” and find the listing for AngularJS Core. There are other packages but this one provides the base Angular framework from the AngularJS Team (so it says). Click Install, select your web project, click OK, then Close to exit the dialogs and NuGet adds the Angular script files to your solution.

nuget-script-folder

Now create a script tag to reference the Angular script in your index.html file.

<script src="Scripts/angular.min.js"></script>

Creating a Basic Angular App Structure

Much of what is recommended here comes from John Papa’s information in this blog post and in his style guide. If you are going beyond this basic structure, reading the source material will give you tips to scale your application architecture.

First, start by adding an app folder to the root of your web project. Within the app folder, add two files: app.module.js and main.js.

The app.module.js file houses a single application-level module for your application. In this example, your application has an application-level module that loads the other modules of the application. The purpose of adding app.module.js as a separate file is to introduce the concept that modules, controllers, services, directives, views, etc. should be defined in their own files. Of course this is negotiable but it’s a good place to start. The contents of the app.module.js file should have the following contents.

(function() {
    'use strict';

    angular.module('app', []);

})();

This example uses an IIFE (immediately-invoked function expression) to immediately execute this code and also to encapsulate its scope. This pattern is used with every module. Also, notice the use of 'use strict'. This triggers modern browsers to run the JavaScript in strict mode. It is optional but it can help you avoid coding problems and many linters such as JSLint complain when it’s not included. The call to angular.module registers the module with the Angular framework.

In the main.js file, create a controller. In John Papa’s blog post, controllers do not use the word ‘controller’ in the file name. At first, I thought this was to save keystrokes, but he makes a good point about how this works with routing. However, there are numerous instances in Angular tutorials where ‘controller’ or ‘ctrl’ are used in the naming (including in John Papa’s style guide) so make the best decision for your projects – just be consistent. Here is the code for the main controller.

(function () {
    'use strict';

    angular
        .module('app')
        .controller('Main', main);

    function main() {
        var vm = this;
        vm.food = 'pizza';
    }

})();

In this IIFE, the controller is registered with the app module. An argument could be made to create a main module with which to associate the controller but being that this is the only controller in the project, this can be left out. Once the project grows in complexity, you should consider registering the controllers with feature-level or section-level modules and leave the application-level app module for registering these various sub-modules (read more in the style guide).

The function main is the controller itself. This controller is configured to use the controllerAs syntax. Again, John Papa details the benefits in his style guide. From the perspective of writing the controller, the big notable is that the properties and methods that you apply to scope are defined on this instead of an injected $scope parameter. Most examples I have seen online for Angular use $scope so this may be new to you. In addition, notice the use of the variable vm to capture the scope. This practice helps to avoid any confusion if/when you define nested functions also using the this keyword.

Finally, take a look at the index.html view. Here is the code.

<!DOCTYPE html>

<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>Sriracha sauce is great with {{vm.food}}!</p>

    <script src="Scripts/angular.min.js"></script>
    <script src="app/app.module.js"></script>
    <script src="app/main.js"></script>

</body>
</html>

First you see the ng-app directive set to the app module to bootstrap the application. On the body tag you see the use of the controller as syntax in the view. Something to note, the use of the name vm in the view has no correlation to its use in the controller. The two variables can have different names. Next, you see the basic example of using the vm scope with a simple input scenario where the value of the input is bound to the expression vm.food. Finally, all of the scripts are referenced on the page.

After completing these steps, your application structure looks like the following.

final-structure

When you run the application you should be able to pair your favorite food with the infamous Rooster Sauce.

final-interface

Conclusion

To those of you who have been using the full breadth of ASP.NET over the years, using static HTML files may seem like a foreign concept and admittedly the ASP.NET project templates tend to favor server-side views.

However, now you have a project that feels like other ASP.NET projects you have worked on. You are still pressing F5 to startup IIS Express and the HTML and JavaScript editors are the ones that you are used to using.

You also have a starter Angular application with basic separation of concerns. You even have a naming convention to use for your modules and controllers as well.

If you would like to download the finished project, you can do so on GitHub.

In the next post, you will learn about a Visual Studio tool called Browser Link. It provides useful features especially for client-side development but there are some tricks to setting it up with static files. Until then, enjoy experimenting with your new Angular project.

68 thoughts on “Your First Angular Project in Visual Studio”

  1. Currently learning AngularJS for work and found this to be the best tutorial for starting off straight from a blank VS project. Good read!

  2. Aaron,
    This tutorial is the best out of many:
    – plain English, easy to understand
    – detailed explaination on every line
    – straighforward
    – no Angular version dependency, in a contrast, AngularJS’ “A first example” (https://docs.angularjs.org/guide/concepts) has works only w/ 1.4.1, which took me a while to find out.

    A small question on the IIFE, can you explain why it’s ending
    })();
    I took out the (), no error but page shows
    Sriracha sauce is great with {{vm.food}}!

    Thank you!

    1. Thank you Tom. The role of the immediately-invoked function expression (IIFE) is to act kind of like a constructor. Specifically, the parentheses that you removed are what invoke the function to create the scope. Without invoking it, you simply have a function object that does not yet have a food property defined. Hope that helps.

  3. This example doesn’t work; it shows:
    Sriracha sauce is great with {{vm.food}}!

    Doesn’t matter what is entered in the text box. Angular seems to be ever evolving with no backward compatibility where each weekly release breaks subsequent versions. What version is this for?

    1. I had the same issue, moving the script references before the angular content (head) solved it.

      Great post, very helpful!

      1. had the same prob.
        In index.html I’ve put in html tag this attribute: ng-app=”app”
        after this it worked…

  4. Thanks for the tutorial! I really did a great job explaining the framework structure and the ‘whys’ of setup structure.

    A few requests:
    – link to the Browser Link post
    – further tutorial on best practices for larger scale projects (maybe even discussion on SPA portal type projects)

    thanks!

  5. Really liked this. I’ve been having trouble getting started with Angular and VS2013, and this beautifully simplified the whole process. EXACTLY what I was looking for.

  6. It might be helpful to some people t o have put the link to the completed project at the beginning of the post.

  7. Great introduction. I for the life of me could not figure out how to create a clean project without having to manually create a package.json. I have not tried the tutorial but I read through it and it made alot of sense. Great work. Simple and to the point.

  8. Finally, someone who doesn’t start a tutorial in the middle of it, with a working project. Thanks!

    Btw, if I reference the app.module.js before the main.js like in your code, I get an error: “[$injector:nomod] Module ‘app’ is not available!”.

  9. Hello Aaron Marisi
    Thank you for the tutorial, it really straight forward. looking forward for more on this topic

  10. In case of 0x800a138f error in IE my case for VS2015 user should add into head. It resolves IE compatibility issue.

  11. I am unable to reference the scripts though i have include
    in my html
    and unable to bind the controller

  12. Just tried using VS 2010. Funny thing:
    1) F5 won’t work, complained in angular.min.js, Node.prototype is null or not an object, line 188,
    var Tf=F.Node.prototype.contains||function(a){return!!(this.compareDocumentPosition(a)&16)}.
    2) Independently launch IISExpress accessing index.htm worked!
    Suggestion: Language used here is plain English, better than others. How about more plain English, less technical, particularly less new concept so readers new to A can absorb easily?
    Great work.

  13. Aaron – Can you please let me know if using $scope in them main instead
    angular.module(‘app’).controller(‘Main’, function($Scope){
    var vm = {
    food : ‘pizza’
    };
    $scope.vm = vm;

    would get me Argument ‘Main’ is not a function, got undefined. Can you let me know how i can use this effectively as an alternative to the above example. Sorry for the newbie question.

  14. Excellent article for beginners who want to work with Angularjs with VS. It helps a lot for me.Thanks.

  15. Thank you so much Gentleman!
    It helped me a lot to start out!

    Keep doing the great work!

    Thanks
    Kiru

  16. Hi,
    That was very helpful.
    if I have 2 controller and I wanted to inject VM the 2nd controller, what should I do?

  17. I read the post intro, like a infomercial, I was so excited 😀 LOL
    Thanks for the post mister ^-^

  18. Thank you for the quick, concise, tutorial.
    After using other editors, using Visual Studio is like coming home again.

Comments are closed.