AngularJS Components for ASP.NET MVC Developers, Part 2: Combining MVC and Angular Routing

My original plan for part 2 was to discuss transitioning from Razor to client-side Angular templating. Instead, I am going to move this to part 3 and address a question I answered for a developer today on the LinkedIN AngularJS Developer Group. I feel this fits better as a continuation to part 1 and I will now discuss templating in depth in part 3.

The Problem
The question posed encompasses a common scenario, MVC developers looking to incorporate Angular into their pre-existing applications. My guess is the majority of developers don’t have the luxury of working on greenfield projects, creating a complete SPA (single-page application) from scratch. Instead, you are maintaining an application and would like to harness the power of Angular for newer features, creating ‘mini-SPA’s’ within your site. So how can you get Angular client-side routing to work for part of your site but still maintain your standard server-side MVC routing for the remainder of your application? The answer is actually quite simple.

A Simple Solution
Configure the routes for your Angular driven feature. Remember to include angular-route.js in your page and declare the ngRoute dependency in your module.

Serve up the primary view for your mini-SPA as normal from your controller. In this example it is the Home controller and NgRouteExample action.

Next, in the .cshtml view that is returned, declare your ngApp directive to bootstrap your AngularJS application (unless your are doing this at a higher level) and set the ngView directive.

For demo sake I added links to be handled by ngRoute to the .cshtml view but this is not necessary. You will notice the path returned by the controller will end with #/ , anything past the # fragment ngRoute will take over. Since this is now the root of your Angular application, default.html will be injected into the ngView directive matching the ‘/’ path defined in your route-config.js. Angular routes and MVC routes can be accessed as normal within your mini-SPA pages.

As you can see, Angular routes are prefixed by # while the MVC route is denoted by a typical ‘/{ControllerName}’ pattern. You now have a functioning mini-SPA with client-side routing in your MVC application!
Conclusion
I hope you found this useful in jump-starting the Angular experience within your MVC applications. Until next time, happy coding!

View Code: Github
Part 1: Layouts and Views

Next ArticleAngularJS Components for ASP.NET MVC Developers, Part 3: Angular Templating Fundamentals