Introduction To AngularJS In ASP.NET MVC

Introduction

AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be used freely, modified and shared by others.

Top features Of AngularJS

  • Two Way Data-Binding
    This means that any changes to the model updates the view and any changes to the view updates the model.

  • Dependency Injection
    AngularJS has a built-in Dependency Injection, which makes application easier to develop, maintain and debug in addition to the test.

  • Testing
    Angular will test any of its code through both unit testing and end-to-end testing.

  • Model View Controller
    Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.

To build AngularJS Applications, you should download the script file and it is angular.js. To get the script file, visit https://angularjs.org

Angular MVC

In AngularJS, MVC is implemented in JavaScript and HTML. The view is defined in an HTML form, while the model and controller are implemented in JavaScript. There are several methods by which these components can be put together in AngularJS. 

Views

View in an AngularJS application is created with an HTML. The body of HTML that makes up View will be stored in separate files. 

Directives In AngularJS

AngularJS directives are used in HTML.

  • ng-app − Starts an AngularJS Application.
  • ng-init − Initializes the Application data.
  • ng-model − Binds the values of AngularJS Application data to HTML input controls.
  • ng-repeat − Repeats HTML elements for each item in a collection. 

Controllers in an AngularJS

AngularJS application has controllers to control the flow of data in the application. A Controller is controlled, using ng-controller directive. A controller is a JavaScript object, which contains attributes, properties and functions. Each Controller accepts $scope as a parameter , which refers to the application module that the controller is to control.

Filters In AngularJS

Filters are used to modify the data and can be used in an expression or Directives using pipe character.

  1. uppercase converts text to upper case text.
  2. lowercase converts text to lower case text.
  3. currency formats text in a currency format.
  4. filter- It filters the array to a subset of it based on its provided criteria.
  5. order by- It orders the array based on its provided criteria. 

Module In AngularJS

Modules are used to separate Services, Controllers, Application etc. We define modules in separate JS files. Two types of modules are given below.

  • Application Module − It is used to initialize an application with controller(s).
  • Controller Module − It is used to define Controller.

Scope In AngularJS

Scope is a JavaScript object, which plays the role of joining Controller with the Views. Scope contains the model data. In Controllers, model data is accessed via $scope object.

$scope is passed as a first argument to controller.$scope.message and $scope.type are the models, which are to be used in an HTML page. We have set the values to models, which will be reflected in the application module. We can define the functions as well in $scope.

Custom Directives in AngularJS

Custom Directives are used in AngularJS to enhance the functionality of HTML. Custom Directives are defined, using Directive function. AngularJS application during Bootstrap finds the matching elements and does a one time activity, using its compile() method of the custom Directive. It then processes the element, using link() method of the custom Directive, which is based on the scope of Directive.

Types of Custom Directives

Element Directives activate when a matching element is encountered. Attribute Directive activates when a matching attribute is encountered. CSS Directive activates when a matching CSS style is encountered. Comment Directive activates when a matching comment is encountered.

Internationalization In AngularJS

AngularJS supports an inbuilt internationalization for three types of filters: currency, date and numbers. We only need to use corresponding JS according to locale of the country. By default, it will take the locale of the Browser.

Includes in AngularJS

To achieve embedded HTML pages inside HTML page functionality, the following ways are used − using AJAX. Make a Server call to get the corresponding HTML page and set it in an inner HTML of HTML control. Using Server side Includes JSP, PHP and other Web site Server technologies can include HTML pages. Using AngularJS, we can embed HTML pages within a HTML page, using ng-include Directive. 

AJAX In AngularJS

AngularJS provides $https: control, which works as a Service to retrieve the data from the Server. The Server makes a database call to get the required records. AngularJS needs data in JSON format. Once the data is ready, $https can be used to get the data from the Server. 

Module in AngularJS

A module is a wallet for different sections in your MVC application.

  1. controllers
  2. services
  3. directives
  4. filters

A C# console application has a Main() method which is the base entrance point into the application and it connects together the different parts of the application. Modules are the angular application's equivalent of the Main() method.

Controller in AngularJS

A controller is a JavaScript function. The job of the controller is to build a model for the view to display. The model is the data. In a real time scenarios, the controller calls into a service to retrieve data from the database.

What is $scope in AngularJS

$scope is a parameter that is passed to the controller function by an Angular script framework. We attach the model to the $scope object, which will then be mostly available in the view. With in the view, we can retrieve the data from the scope object and display.

Module that we created to bootstrap the AngularJS Application

It will associate the module name with ng-app directive.

ng-app="myModule"

It will associate the controller using ng-controller directive.

ng-controller="myController"

ng-app directive in AngularJS

There are many directives in angular. You can find the complete list of directives on https://angularjs.org. The ng prefix in the directive stands for angular.

The ng-app directive is a initial point of AngularJS Application. Angular framework will first check for ng-app directive in an HTML page after the entire page is loaded. If ng-app directive is found, angular bootstraps itself and starts to manage the section of the page that has the ng-app directive.

Location to Place the ng-app directive on the page

It should be placed at the root path of the HTML document, that is at the <html> tag level or at the <body> tag level, so that angular can control the entire page.

You can place it on any other HTML element with in the page. When you do this only that element and its children are controlled by angular.

Double curly braces are called binding expressions in AngularJS.

Note

The job of the controller is to build a model for the view. The controller did this by attaching the model to the scope. The $scope is not the model, it's the data that you attach to the scope that is the model. The message property that we have attached to the scope is the model.

The view uses the data-binding expression to retrieve the model from the scope.

This means the controller is not manipulating the document object model directly, thus keeping that clean separation between the model, view and the controller. The controller should only be used for setting up the $scope object and adding behavior it.

In the example below, message is a simple property.

  1. $scope.message = "AngularJS Tutorial";   

In the example below, we have a satya object which is a complex object with 3 properties attached to the view. 

  1. myApp.controller("myController"function ($scope) {  
  2.     var satya = {  
  3.         firstName: 'satyaprakash',  
  4.         lastName: 'samantaray',  
  5.         gender: 'Male'  
  6.     };  
  7.     $scope.satya = satya;  
  8. });   

Within the view, we can then retrieve the satya properties and display them in the view as shown below 

  1. <div ng-controller="myController">      
  2.     <div>First Name : {{ satya.firstName }}</div>  
  3.     <div>Last Name : {{ satya.lastName }}</div>  
  4.     <div>Gender : {{ satya.gender}}</div>  
  5. </div>   

If the controller name is invalid

When the controller name is invalid,

  1. An error is raised. To see the error, use browser developer tools
  2. The binding expressions in the view that are in the scope of the controller is not be evaluated

Another option is, if you are in the development environment, you may use the non-minified version of the AngularJS script, which produces readable error message.

What happens if a property name in the binding expression is invalid

Angular will not report any error. It will simply return null or undefined.

Tips to recover from above mentioned error or invalid names.

Put module, controller and register the controller with the module should be in one line.

Steps to Create a Simple Application To Understand Better

Step 1

Create a MVC application named “AngularJSIntro”.

To build AngularJS Applications, you should download the script file and it is angular.js. To get the script file, visit https://angularjs.org. 

After download then add in the project by creating a new folder called “Scripts”. Then check “angular.js” scripting file is added or not.

AngularJS

AngularJS

Step 2

Create a controller class file named “ProfileController.cs”.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace AngularJSIntro.Controllers  
  8. {  
  9.     public class ProfileController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Profile/  
  13.   
  14.         public ActionResult Flair()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.     }  
  20. }   

Code Description

Here “ProfileController” is the name of the controller class file.

Here “Flair” is the name of the controller action method.

AngularJS

Step 3

Create a javascript file named “Script.js”. Then add this script file in “Scripts” folder.

AngularJS

Code Ref 

  1. var myApp = angular  
  2.                .module("myModule", [])  
  3.                .controller("myController"function ($scope) {  
  4.                    var Profile = {  
  5.                        Name: "Satyaprakash Samantaray",  
  6.                        Site: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray",  
  7.                        Flair: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png"  
  8.                    };  
  9.                    $scope.Profile = Profile;  
  10.                });   

Code Description

Creating a module in angular is straightforward. Use the angular object's module() method to create a module. The angular object is provided by angular script. The following example, creates module. 

  1. var myApp = angular  
  2.   
  3. .module("myModule", [])   

The first parameter specifies the name of the module. The second parameter specifies the dependencies for this module.

A module can depend on other modules. The module that we are creating is not dependent on any other external modules, so I am passing an empty array as the value for the second parameter.

  1. .module("myModule", [])   

To create a controller in angularjs , create a JavaScript function and assign it to a variable.

  1. .controller("myController"function ($scope) {   

Use module object's controller function to register the controller with the module.

Creating the controller and registering with the module are all done in one line. 

  1. myApp .controller("myController"function ($scope) {  
  2.                    var Profile = {  
  3.                        Name: "Satyaprakash Samantaray",  
  4.                        Site: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray",  
  5.                        Flair: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png"  
  6.                    };  
  7.                    $scope.Profile = Profile;  
  8.                });   

In the example below, we have an Profile object which is a complex object with 3 properties attached to the view. 

  1. var Profile = {  
  2.                        Name: "Satyaprakash Samantaray",  
  3.                        Site: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray",  
  4.                        Flair: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png"  
  5.                    };  
  6.                    $scope.Profile = Profile;   

In the example below, Profile is a simple property to show the properties value through view.

  1. $scope.Profile = Profile;   

Name: "Satyaprakash Samantaray"

Here Name property will show the value of Name property.

Site: "http://www.c-sharpcorner.com/members/satyaprakash-samantaray",

Here Site property will show the value of Site property.

Flair: http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png

Here Flair property will show the image value of Flair property.

AngularJS

Step 4

Create a view named “Flair.cshtml”.

Code Ref 

  1. <html ng-app="myModule">  
  2.   
  3. <head>  
  4.     <title>Satyaprakash Angularjs Introduction</title>  
  5.     <script src="Scripts/angular.js"></script>  
  6.     <script src="Scripts/Script.js"></script>  
  7. </head>  
  8.   
  9. <body>  
  10.     <div ng-controller="myController" style="font-family:Arial Black;">  
  11.         <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYAPRAKASH's INTRODUCTION TO ANGULARJS</h2>  
  12.         <fieldset>  
  13.             <legend style="font-family:Arial Black;color:orangered">C# CORNER PROFILE INFORMATION</legend>  
  14.             <div ng-controller="myController">  
  15.                 <div style="color:blue">  
  16.                     Name : {{ Profile.Name }}  
  17.                 </div>  
  18.                 <div style="color:green">  
  19.                     Site Url : {{ Profile.Site }}  
  20.                 </div>  
  21.                 <div>  
  22.                     <img src="{{Profile.Flair}}"  
  23.                          alt="{{ Profile.Name + ' Flair' }}"  
  24.                          style="height:60px; width:300px" />  
  25.                 </div>  
  26.             </div>  
  27.         </fieldset>  
  28.     </div>  
  29.     <footer>  
  30.         <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  31.     </footer>  
  32. </body>  
  33. </html>   

Code Description

Here I added script path references.

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

This one I added To build AngularJS Applications.

  1. <script src="Scripts/Script.js"></script>   

Here I added controller related information. In this script file The controller is not manipulating the document object model directly, thus keeping that clean separation between the model, view and the controller. The controller should only be used for setting up the $scope object and adding behavior it.

we have an Profile object which is a complex object with 3 properties attached to the view.

Here I added “ng-controller” directive name i.e. “myController” in Div tag and main directive or parent directive “ng-app” directive name i.e. “myModule” in Html tag. Because of this “ng-app” directive we can access “ng-controller” directive. Both directives we mentioned in “Script.Js” file. 

  1. <div ng-controller="myController">  
  2.         <div style="color:blue">  
  3.                     Name : {{ Profile.Name }}  
  4.         </div>  
  5.         <div style="color:green">  
  6.                     Site Url : {{ Profile.Site }}  
  7.         </div>  
  8.          <div>  
  9.                     <img src="{{Profile.Flair}}"  
  10.                      alt="{{ Profile.Name + ' Flair' }}"  
  11.                      style="height:60px; width:300px" />  
  12.          </div>  
  13.  </div>   

Here we can see properties values using profile object as defined in “Script.Js” file.

Name : {{ Profile.Name }}

It will show the user name.

Site Url : {{ Profile.Site }}

It will show the site name. 

  1. <img src="{{Profile.Flair}}" alt="{{ Profile.Name + ' Flair' }}" style="height:60px; width:300px" />   

It will show c-sharpcorner related flair png image with style height and width.

If image not found , it will show you the alternate text of image i.e. :

Satyaprakash Samantaray Flair.

  1. alt="{{ Profile.Name + ' Flair' }}"   

Note

This flair png image you can get from your Account in Flair section.

AngularJS

AngularJS

Step 5

Set start page during first time load of your UI.

Code Ref 

  1. public static void RegisterRoutes(RouteCollection routes)  
  2.         {  
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.             routes.MapRoute(  
  6.                 name: "Default",  
  7.                 url: "{controller}/{action}/{id}",  
  8.                 defaults: new { controller = "Profile", action = "Flair", id = UrlParameter.Optional }  
  9.             );  
  10.         }   

Code Description

Here name of the controller name is : “Profile” .

Here name of the controller action method name is : “Flair” .

AngularJS

OUTPUT

The name of the url is : https://localhost:51315/Profile/Flair

AngularJS

Here you can get your related properties values like Name , Site Name and Flair Png Image file.

Here I changed flair properties value from

http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png to

http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair1.png

So, the output will be ,

AngularJS

Here image path is not found as in server. So, the instead of image image’s alternate name is showing. I.e. : Satyaprakash Samantaray Flair.

In footer section it is showing Today’s Date Time.

AngularJS

SUMMARY

  1. What is AngularJS.
  2. Different parts of AngularJS.
  3. How to download script file to make functionalities in AngularJS application.
  4. How to implement the logic of AngularJS in Asp.net MVC application.


Similar Articles