Using AngularJS for Single Page Applications (SPAs) with ASP.NET Core
By Venkata Koppaka and Scott Addie
In this article, you will learn how to build a SPA-style ASP.NET application using AngularJS.
View or download sample code ((xref:)how to download)
What is AngularJS?
AngularJS is a modern JavaScript framework from Google commonly used to work with Single Page Applications (SPAs). AngularJS is open sourced under MIT license, and the development progress of AngularJS can be followed on its GitHub repository. The library is called Angular because HTML uses angular-shaped brackets.
AngularJS is not a DOM manipulation library like jQuery, but it uses a subset of jQuery called jQLite. AngularJS is primarily based on declarative HTML attributes that you can add to your HTML tags. You can try AngularJS in your browser using the Code School website or W3Schools website.
This article focuses on AngularJS with some notes on where Angular is heading.
Getting started
To start using AngularJS in your ASP.NET application, you must either install it as part of your project, or reference it from a content delivery network (CDN).
Installation
There are several ways to add AngularJS to your application. If you’re starting a new ASP.NET Core web application in Visual Studio, you can add AngularJS using the built-in Bower support. Open bower.json, and add an entry to the dependencies
property:
[!code-jsonMain]
1: {
2: "name": "ASP.NET",
3: "private": true,
4: "dependencies": {
5: "bootstrap": "3.3.5",
6: "jquery": "2.1.4",
7: "jquery-validation": "1.14.0",
8: "jquery-validation-unobtrusive": "3.2.4",
9: "angular": "1.5.7",
10: "angular-route": "1.5.7"
11: }
12: }
Upon saving the bower.json file, Angular will be installed in your project’s wwwroot/lib folder. Additionally, it will be listed within the Dependencies/Bower
folder. See the screenshot below.
Next, add a <script>
reference to the bottom of the <body>
section of your HTML page or *_Layout.cshtml* file, as shown here:
[!code-htmlMain]
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <meta charset="utf-8" />
5: <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6: <title>@ViewData["Title"] - AngularSample</title>
7:
8: <environment names="Development">
9: <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
10: <link rel="stylesheet" href="~/css/site.css" />
11: </environment>
12: <environment names="Staging,Production">
13: <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/css/bootstrap.min.css"
14: asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
15: asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
16: <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
17: </environment>
18: </head>
19: <body>
20: <div class="navbar navbar-inverse navbar-fixed-top">
21: <div class="container">
22: <div class="navbar-header">
23: <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
24: <span class="sr-only">Toggle navigation</span>
25: <span class="icon-bar"></span>
26: <span class="icon-bar"></span>
27: <span class="icon-bar"></span>
28: </button>
29: <a asp-controller="Home" asp-action="Index" class="navbar-brand">AngularSample</a>
30: </div>
31: <div class="navbar-collapse collapse">
32: <ul class="nav navbar-nav">
33: <li><a asp-controller="Home" asp-action="Index">Home</a></li>
34: <li><a asp-controller="Home" asp-action="About">About</a></li>
35: <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
36: </ul>
37: </div>
38: </div>
39: </div>
40: <div class="container body-content">
41: @RenderBody()
42: <hr />
43: <footer>
44: <p>© 2015 - AngularSample</p>
45: </footer>
46: </div>
47:
48: <environment names="Development">
49: <script src="~/lib/jquery/dist/jquery.js"></script>
50: <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
51: <script src="~/lib/angular/angular.js"></script>
52: </environment>
53: <environment names="Staging,Production">
54: <script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
55: asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
56: asp-fallback-test="window.jQuery">
57: </script>
58: <script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/bootstrap.min.js"
59: asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
60: asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
61: </script>
62: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"
63: asp-fallback-src="~/lib/angular/angular.min.js"
64: asp-fallback-test="window.angular">
65: </script>
66: <script src="~/js/site.min.js" asp-append-version="true"></script>
67: </environment>
68:
69: @RenderSection("scripts", required: false)
70: </body>
71: </html>
It’s recommended that production applications utilize CDNs for common libraries like AngularJS. You can reference AngularJS from one of several CDNs, such as this one:
[!code-htmlMain]
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <meta charset="utf-8" />
5: <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6: <title>@ViewData["Title"] - AngularSample</title>
7:
8: <environment names="Development">
9: <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
10: <link rel="stylesheet" href="~/css/site.css" />
11: </environment>
12: <environment names="Staging,Production">
13: <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/css/bootstrap.min.css"
14: asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
15: asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
16: <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
17: </environment>
18: </head>
19: <body>
20: <div class="navbar navbar-inverse navbar-fixed-top">
21: <div class="container">
22: <div class="navbar-header">
23: <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
24: <span class="sr-only">Toggle navigation</span>
25: <span class="icon-bar"></span>
26: <span class="icon-bar"></span>
27: <span class="icon-bar"></span>
28: </button>
29: <a asp-controller="Home" asp-action="Index" class="navbar-brand">AngularSample</a>
30: </div>
31: <div class="navbar-collapse collapse">
32: <ul class="nav navbar-nav">
33: <li><a asp-controller="Home" asp-action="Index">Home</a></li>
34: <li><a asp-controller="Home" asp-action="About">About</a></li>
35: <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
36: </ul>
37: </div>
38: </div>
39: </div>
40: <div class="container body-content">
41: @RenderBody()
42: <hr />
43: <footer>
44: <p>© 2015 - AngularSample</p>
45: </footer>
46: </div>
47:
48: <environment names="Development">
49: <script src="~/lib/jquery/dist/jquery.js"></script>
50: <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
51: <script src="~/lib/angular/angular.js"></script>
52: </environment>
53: <environment names="Staging,Production">
54: <script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
55: asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
56: asp-fallback-test="window.jQuery">
57: </script>
58: <script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/bootstrap.min.js"
59: asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
60: asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
61: </script>
62: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"
63: asp-fallback-src="~/lib/angular/angular.min.js"
64: asp-fallback-test="window.angular">
65: </script>
66: <script src="~/js/site.min.js" asp-append-version="true"></script>
67: </environment>
68:
69: @RenderSection("scripts", required: false)
70: </body>
71: </html>
Once you have a reference to the angular.js script file, you’re ready to begin using AngularJS in your web pages.
Key components
AngularJS includes a number of major components, such as directives, templates, repeaters, modules, controllers, components, component router and more. Let’s examine how these components work together to add behavior to your web pages.
Directives
AngularJS uses directives to extend HTML with custom attributes and elements. AngularJS directives are defined via data-ng-*
or ng-*
prefixes (ng
is short for angular). There are two types of AngularJS directives:
Primitive Directives: These are predefined by the Angular team and are part of the AngularJS framework.
Custom Directives: These are custom directives that you can define.
One of the primitive directives used in all AngularJS applications is the ng-app
directive, which bootstraps the AngularJS application. This directive can be applied to the <body>
tag or to a child element of the body. Let’s see an example in action. Assuming you’re in an ASP.NET project, you can either add an HTML file to the wwwroot
folder, or add a new controller action and an associated view. In this case, I’ve added a new Directives
action method to HomeController.cs
. The associated view is shown here:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Directives</h1>
7: {{2+2}}
8: <script src="~/lib/angular/angular.js"></script>
9: </body>
10: </html>
To keep these samples independent of one another, I’m not using the shared layout file. You can see that we decorated the body tag with the ng-app
directive to indicate this page is an AngularJS application. The {{2+2}}
is an Angular data binding expression that you will learn more about in a moment. Here is the result if you run this application:
Other primitive directives in AngularJS include:
ng-controller
Determines which JavaScript controller is bound to which view.
ng-model
Determines the model to which the values of an HTML element’s properties are bound.
ng-init
Used to initialize the application data in the form of an expression for the current scope.
ng-if
Removes or recreates the given HTML element in the DOM based on the truthiness of the expression provided.
ng-repeat
Repeats a given block of HTML over a set of data.
ng-show
Shows or hides the given HTML element based on the expression provided.
For a full list of all primitive directives supported in AngularJS, please refer to the directive documentation section on the AngularJS documentation website.
Data binding
AngularJS provides data binding support out-of-the-box using either the ng-bind
directive or a data binding expression syntax such as {{expression}}
. AngularJS supports two-way data binding where data from a model is kept in synchronization with a view template at all times. Any changes to the view are automatically reflected in the model. Likewise, any changes in the model are reflected in the view.
Create either an HTML file or a controller action with an accompanying view named Databinding
. Include the following in the view:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Databinding</h1>
7:
8: <div ng-init="firstName='John'; lastName='Doe';">
9: <strong>First name:</strong> {{firstName}} <br />
10: <strong>Last name:</strong> <span ng-bind="lastName" />
11: </div>
12:
13: <script src="~/lib/angular/angular.js"></script>
14: </body>
15: </html>
Notice that you can display model values using either directives or data binding (ng-bind
). The resulting page should look like this:
Templates
Templates in AngularJS are just plain HTML pages decorated with AngularJS directives and artifacts. A template in AngularJS is a mixture of directives, expressions, filters, and controls that combine with HTML to form the view.
Add another view to demonstrate templates, and add the following to it:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Templates</h1>
7:
8: <div ng-init="personName='John Doe'">
9: <input ng-model="personName" /> {{personName}}
10: </div>
11:
12: <script src="~/lib/angular/angular.js"></script>
13: </body>
14: </html>
The template has AngularJS directives like ng-app
, ng-init
, ng-model
and data binding expression syntax to bind the personName
property. Running in the browser, the view looks like the screenshot below:
If you change the name by typing in the input field, you will see the text next to the input field dynamically update, showing Angular two-way data binding in action.
Expressions
Expressions in AngularJS are JavaScript-like code snippets that are written inside the {{ expression }}
syntax. The data from these expressions is bound to HTML the same way as ng-bind
directives. The main difference between AngularJS expressions and regular JavaScript expressions is that AngularJS expressions are evaluated against the $scope
object in AngularJS.
The AngularJS expressions in the sample below bind personName
and a simple JavaScript calculated expression:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Expressions</h1>
7:
8: <div ng-init="personName='John Doe'">
9: Person's name is: {{personName}} <br />
10: Simple JavaScript calculation of 1 + 2: {{1+2}}
11: </div>
12:
13: <script src="~/lib/angular/angular.js"></script>
14: </body>
15: </html>
The example running in the browser displays the personName
data and the results of the calculation:
Repeaters
Repeating in AngularJS is done via a primitive directive called ng-repeat
. The ng-repeat
directive repeats a given HTML element in a view over the length of a repeating data array. Repeaters in AngularJS can repeat over an array of strings or objects. Here is a sample usage of repeating over an array of strings:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Repeaters</h1>
7:
8: <div ng-init="names=['John Doe', 'Mary Jane', 'Bob Parker']">
9: <ul>
10: <li ng-repeat="name in names">
11: {{name}}
12: </li>
13: </ul>
14: </div>
15:
16: <script src="~/lib/angular/angular.js"></script>
17: </body>
18: </html>
The repeat directive outputs a series of list items in an unordered list, as you can see in the developer tools shown in this screenshot:
Here is an example that repeats over an array of objects. The ng-init
directive establishes a names
array, where each element is an object containing first and last names. The ng-repeat
assignment, name in names
, outputs a list item for every array element.
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Repeaters2</h1>
7:
8: <div ng-init="names=[
9: {firstName:'John', lastName:'Doe'},
10: {firstName:'Mary', lastName:'Jane'},
11: {firstName:'Bob', lastName:'Parker'}]">
12: <ul>
13: <li ng-repeat="name in names">
14: {{name.firstName + ' ' + name.lastName}}
15: </li>
16: </ul>
17: </div>
18:
19: <script src="~/lib/angular/angular.js"></script>
20: </body>
21: </html>
The output in this case is the same as in the previous example.
Angular provides some additional directives that can help provide behavior based on where the loop is in its execution.
$index
Use $index
in the ng-repeat
loop to determine which index position your loop currently is on.
$even
and $odd
Use $even
in the ng-repeat
loop to determine whether the current index in your loop is an even indexed row. Similarly, use $odd
to determine if the current index is an odd indexed row.
$first
and $last
Use $first
in the ng-repeat
loop to determine whether the current index in your loop is the first row. Similarly, use $last
to determine if the current index is the last row.
Below is a sample that shows $index
, $even
, $odd
, $first
, and $last
in action:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app>
6: <h1>Repeaters2</h1>
7:
8: <div ng-init="names=[
9: {firstName:'John', lastName:'Doe'},
10: {firstName:'Mary', lastName:'Jane'},
11: {firstName:'Bob', lastName:'Parker'}]">
12: <ul>
13: <li ng-repeat="name in names">
14: {{name.firstName + ' ' + name.lastName}} at index {{$index}}
15: <span ng-show="{{$first}}">, the first position</span>
16: <span ng-show="{{$last}}">, the last position</span>
17: <span ng-show="{{$odd}}">,which is odd-numbered.</span>
18: <span ng-show="{{$even}}">,which is even-numbered.</span>
19: </li>
20: </ul>
21: </div>
22:
23: <script src="~/lib/angular/angular.js"></script>
24: </body>
25: </html>
Here is the resulting output:
$scope
$scope
is a JavaScript object that acts as glue between the view (template) and the controller (explained below). A view template in AngularJS only knows about the values attached to the $scope
object in the controller.
[!NOTE] In the MVVM world, the
$scope
object in AngularJS is often defined as the ViewModel. The AngularJS team refers to the$scope
object as the Data-Model. Learn more about Scopes in AngularJS.
Below is a simple example showing how to set properties on $scope
within a separate JavaScript file, scope.js:
[!code-htmlMain]
1: var personApp = angular.module('personApp', []);
2: personApp.controller('personController', ['$scope', function ($scope) {
3: $scope.name = 'Mary Jane';
4: }]);
Observe the $scope
parameter passed to the controller on line 2. This object is what the view knows about. On line 3, we are setting a property called “name” to “Mary Jane”.
What happens when a particular property is not found by the view? The view defined below refers to “name” and “age” properties:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app="personApp">
6: <h1>Scope</h1>
7:
8: <div ng-controller="personController">
9: <strong>Name:</strong> {{name}} <br />
10: <strong>Missing Property (age):</strong> {{age}}
11: </div>
12:
13: <script src="~/lib/angular/angular.js"></script>
14: <script src="~/app/scope.js"></script>
15: </body>
16: </html>
Notice on line 9 that we are asking Angular to show the “name” property using expression syntax. Line 10 then refers to “age”, a property that does not exist. The running example shows the name set to “Mary Jane” and nothing for age. Missing properties are ignored.
Modules
A module in AngularJS is a collection of controllers, services, directives, etc. The angular.module()
function call is used to create, register, and retrieve modules in AngularJS. All modules, including those shipped by the AngularJS team and third party libraries, should be registered using the angular.module()
function.
Below is a snippet of code that shows how to create a new module in AngularJS. The first parameter is the name of the module. The second parameter defines dependencies on other modules. Later in this article, we will be showing how to pass these dependencies to an angular.module()
method call.
Use the ng-app
directive to represent an AngularJS module on the page. To use a module, assign the name of the module, personApp
in this example, to the ng-app
directive in our template.
Controllers
Controllers in AngularJS are the first point of entry for your code. The <module name>.controller()
function call is used to create and register controllers in AngularJS. The ng-controller
directive is used to represent an AngularJS controller on the HTML page. The role of the controller in Angular is to set state and behavior of the data model ($scope
). Controllers should not be used to manipulate the DOM directly.
Below is a snippet of code that registers a new controller. The personApp
variable in the snippet references an Angular module, which is defined on line 2.
[!code-javascriptMain]
1: // module
2: var personApp = angular.module('personApp', []);
3:
4: // controller
5: personApp.controller('personController', function ($scope) {
6: $scope.firstName = "Mary";
7: $scope.lastName = "Jane"
8: });
The view using the ng-controller
directive assigns the controller name:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app="personApp">
6: <h1>Controllers</h1>
7:
8: <div ng-controller="personController">
9: <strong>First Name:</strong> {{firstName}} <br />
10: <strong>Last Name:</strong> {{lastName}}
11: </div>
12:
13: <script src="~/lib/angular/angular.js"></script>
14: <script src="~/app/controllers.js"></script>
15: </body>
16: </html>
The page shows “Mary” and “Jane” that correspond to the firstName
and lastName
properties attached to the $scope
object:
Components
Components in Angular 1.5.x allow for the encapsulation and capability of creating individual HTML elements. In Angular 1.4.x you could achieve the same feature using the .directive() method.
By using the .component() method, development is simplified gaining the functionality of the directive and the controller. Other benefits include; scope isolation, best practices are inherent, and migration to Angular 2 becomes an easier task. The <module name>.component()
function call is used to create and register components in AngularJS.
Below is a snippet of code that registers a new component. The personApp
variable in the snippet references an Angular module, which is defined on line 2.
[!code-javascriptMain]
1: // module
2: var personApp = angular.module('personApp', []);
3:
4: // controller
5: var PersonController = function(){
6:
7: var vm = this;
8: vm.firstName = "Aftab";
9: vm.lastName = "Ansari";
10: }
11:
12: // component
13: personApp.component('personComponent', {
14: templateUrl:'/app/partials/personcomponent.html',
15: controller:PersonController,
16: controllerAs:'vm'
17:
18: });
The view where we are displaying the custom HTML element.
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app="personApp">
6: <h1>Components</h1>
7:
8: <person-component></person-component>
9:
10: <script src="~/lib/angular/angular.js"></script>
11: <script src="~/app/components.js"></script>
12: </body>
13: </html>
The associated template used by component:
[!code-htmlMain]
1: <div>
2: <strong>First Name:</strong> {{vm.firstName}} <br />
3: <strong>Last Name:</strong> {{vm.lastName}}
4: </div>
The page shows “Aftab” and “Ansari” that correspond to the firstName
and lastName
properties attached to the vm
object:
Services
Services in AngularJS are commonly used for shared code that is abstracted away into a file which can be used throughout the lifetime of an Angular application. Services are lazily instantiated, meaning that there will not be an instance of a service unless a component that depends on the service gets used. Factories are an example of a service used in AngularJS applications. Factories are created using the myApp.factory()
function call, where myApp
is the module.
Below is an example that shows how to use factories in AngularJS:
[!code-javascriptMain]
1: personApp.factory('personFactory', function () {
2: function getName() {
3: return "Mary Jane";
4: }
5:
6: var service = {
7: getName: getName
8: };
9:
10: return service;
11: });
To call this factory from the controller, pass personFactory
as a parameter to the controller
function:
personApp.controller('personController', function($scope,personFactory) {
$scope.name = personFactory.getName();
});
Using services to talk to a REST endpoint
Below is an end-to-end example using services in AngularJS to interact with an ASP.NET Core Web API endpoint. The example gets data from the Web API and displays the data in a view template. Let’s start with the view first:
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app="PersonsApp">
6: <h1>People</h1>
7:
8: <div ng-controller="personController">
9: <ul>
10: <li ng-repeat="person in people">
11: <h2>{{person.FirstName}} {{person.LastName}}</h2>
12: </li>
13: </ul>
14: </div>
15:
16: <script src="~/lib/angular/angular.js"></script>
17: <script src="~/app/personApp.js"></script>
18: <script src="~/app/personFactory.js"></script>
19: <script src="~/app/personController.js"></script>
20: </body>
21: </html>
In this view, we have an Angular module called PersonsApp
and a controller called personController
. We are using ng-repeat
to iterate over the list of persons. We are referencing three custom JavaScript files on lines 17-19.
The personApp.js file is used to register the PersonsApp
module; and, the syntax is similar to previous examples. We are using the angular.module
function to create a new instance of the module that we will be working with.
[!code-javascriptMain]
1: (function () {
2: 'use strict';
3: var app = angular.module('PersonsApp', []);
4: })();
Let’s take a look at personFactory.js, below. We are calling the module’s factory
method to create a factory. Line 12 shows the built-in Angular $http
service retrieving people information from a web service.
[!code-javascriptMain]
1: (function () {
2: 'use strict';
3:
4: var serviceId = 'personFactory';
5:
6: angular.module('PersonsApp').factory(serviceId,
7: ['$http', personFactory]);
8:
9: function personFactory($http) {
10:
11: function getPeople() {
12: return $http.get('/api/people');
13: }
14:
15: var service = {
16: getPeople: getPeople
17: };
18:
19: return service;
20: }
21: })();
In personController.js, we are calling the module’s controller
method to create the controller. The $scope
object’s people
property is assigned the data returned from the personFactory (line 13).
[!code-javascriptMain]
1: (function () {
2: 'use strict';
3:
4: var controllerId = 'personController';
5:
6: angular.module('PersonsApp').controller(controllerId,
7: ['$scope', 'personFactory', personController]);
8:
9: function personController($scope, personFactory) {
10: $scope.people = [];
11:
12: personFactory.getPeople().then(
13: // callback function for successful http request
14: function success(response) {
15: $scope.people = response.data;
16: },
17: // callback function for error in http request
18: function error(response) {
19: // log errors
20: }
21: );
22: }
23: })();
Let’s take a quick look at the Web API and the model behind it. The Person
model is a POCO (Plain Old CLR Object) with Id
, FirstName
, and LastName
properties:
[!code-csharpMain]
1: namespace AngularSample.Models
2: {
3: public class Person
4: {
5: public int Id { get; set; }
6: public string FirstName { get; set; }
7: public string LastName { get; set; }
8: }
9: }
The Person
controller returns a JSON-formatted list of Person
objects:
[!code-csharpMain]
1: using AngularSample.Models;
2: using Microsoft.AspNetCore.Mvc;
3: using System.Collections.Generic;
4:
5: namespace AngularSample.Controllers.Api
6: {
7: public class PersonController : Controller
8: {
9: [Route("/api/people")]
10: public JsonResult GetPeople()
11: {
12: var people = new List<Person>()
13: {
14: new Person { Id = 1, FirstName = "John", LastName = "Doe" },
15: new Person { Id = 1, FirstName = "Mary", LastName = "Jane" },
16: new Person { Id = 1, FirstName = "Bob", LastName = "Parker" }
17: };
18:
19: // default behavior will convert fields in model to camelCase in Json object
20: return Json(people);
21: }
22: }
23: }
Let’s see the application in action:
You can view the application’s structure on GitHub.
[!NOTE] For more on structuring AngularJS applications, see John Papa’s Angular Style Guide
[!NOTE] To create AngularJS module, controller, factory, directive and view files easily, be sure to check out Sayed Hashimi’s SideWaffle template pack for Visual Studio. Sayed Hashimi is a Senior Program Manager on the Visual Studio Web Team at Microsoft and SideWaffle templates are considered the gold standard. At the time of this writing, SideWaffle is available for Visual Studio 2012, 2013, and 2015.
Routing and multiple views
AngularJS has a built-in route provider to handle SPA (Single Page Application) based navigation. To work with routing in AngularJS, you must add the angular-route
library using Bower. You can see in the bower.json file referenced at the start of this article that we are already referencing it in our project.
After you install the package, add the script reference (angular-route.js) to your view.
Now let’s take the Person App we have been building and add navigation to it. First, we will make a copy of the app by creating a new PeopleController
action called Spa
and a corresponding Spa.cshtml
view by copying the Index.cshtml view in the People
folder. Add a script reference to angular-route
(see line 11). Also add a div
marked with the ng-view
directive (see line 6) as a placeholder to place views in. We are going to be using several additional .js files which are referenced on lines 13-16.
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app="personApp">
6: <div ng-view>
7:
8: </div>
9:
10: <script src="~/lib/angular/angular.js"></script>
11: <script src="~/lib/angular-route/angular-route.js"></script>
12:
13: <script src="~/app/personModule.js"></script>
14: <script src="~/app/personRoutes.js"></script>
15: <script src="~/app/personListController.js"></script>
16: <script src="~/app/personDetailController.js"></script>
17: </body>
18: </html>
Let’s take a look at personModule.js file to see how we are instantiating the module with routing. We are passing ngRoute
as a library into the module. This module handles routing in our application.
[!code-javascriptMain]
1: var personApp = angular.module('personApp', ['ngRoute']);
The personRoutes.js file, below, defines routes based on the route provider. Lines 4-7 define navigation by effectively saying, when a URL with /persons
is requested, use a template called partials/personlist
by working through personListController
. Lines 8-11 indicate a detail page with a route parameter of personId
. If the URL doesn’t match one of the patterns, Angular defaults to the /persons
view.
[!code-javascriptMain]
1: personApp.config(['$routeProvider',
2: function ($routeProvider) {
3: $routeProvider.
4: when('/persons', {
5: templateUrl: '/app/partials/personlist.html',
6: controller: 'personListController'
7: }).
8: when('/persons/:personId', {
9: templateUrl: '/app/partials/persondetail.html',
10: controller: 'personDetailController'
11: }).
12: otherwise({
13: redirectTo: '/persons'
14: })
15: }
16: ]);
The personlist.html
file is a partial view containing only the HTML needed to display person list.
[!code-htmlMain]
1: <div>
2: <h1>PERSONS PAGE</h1>
3: <span ng-bind="message"/>
4: </div>
The controller is defined by using the module’s controller
function in personListController.js.
[!code-javascriptMain]
1: personApp.controller('personListController', function ($scope) {
2: $scope.message = "You are on the Persons List Page.";
3: })
If we run this application and navigate to the people/spa#/persons
URL, we will see:
If we navigate to a detail page, for example people/spa#/persons/2
, we will see the detail partial view:
You can view the full source and any files not shown in this article on GitHub.
Event Handlers
There are a number of directives in AngularJS that add event-handling capabilities to the input elements in your HTML DOM. Below is a list of the events that are built into AngularJS.
ng-click
ng-dbl-click
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-keydown
ng-keyup
ng-keypress
ng-change
[!NOTE] You can add your own event handlers using the custom directives feature in AngularJS.
Let’s look at how the ng-click
event is wired up. Create a new JavaScript file named eventHandlerController.js, and add the following to it:
[!code-javascriptMain]
1: personApp.controller('eventHandlerController', function ($scope) {
2: $scope.firstName = 'Mary';
3: $scope.lastName = 'Jane';
4:
5: $scope.sayName = function () {
6: alert('Welcome, ' + $scope.firstName + ' ' + $scope.lastName);
7: }
8: });
Notice the new sayName
function in eventHandlerController
on line 5 above. All the method is doing for now is showing a JavaScript alert to the user with a welcome message.
The view below binds a controller function to an AngularJS event. Line 9 has a button on which the ng-click
Angular directive has been applied. It calls our sayName
function, which is attached to the $scope
object passed to this view.
[!code-htmlMain]
1: @{
2: Layout = "";
3: }
4: <html>
5: <body ng-app="personApp">
6: <div ng-controller="eventHandlerController">
7: <strong>First Name:</strong> {{firstName}} <br />
8: <strong>Last Name:</strong> {{lastName}} <br />
9: <input ng-click="sayName()" type="button" value="Say Name" />
10: </div>
11: <script src="~/lib/angular/angular.js"></script>
12: <script src="~/lib/angular-route/angular-route.js"></script>
13:
14: <script src="~/app/personModule.js"></script>
15: <script src="~/app/eventHandlerController.js"></script>
16: </body>
17: </html>
The running example demonstrates that the controller’s sayName
function is called automatically when the button is clicked.
For more detail on AngularJS built-in event handler directives, be sure to head to the documentation website of AngularJS.
Additional resources
|