AngularJS Demo: Part 1

This article shows how to create a web application and select Web API + MVC from the wizard.

Step 1

Create a web application and select Web API + MVC from the wizard.

Install AngularJs from the Nuget package.

Install Angular from the nugget package
Step 2

Create a folder called app inside the scripts (if you are using it with TypeScript then the app folder should come under the root folder).

Step 3

Create a JavaScript file called app under the app folder.

Add a reference for the angular-route.js file to the app.js file as in the following.

    /// <reference path="../angular-route.js" />

Add the reference

Now, initialize the app module using the following code. We are initializing the app module only once thoughout the application.

var registrationModule = angular.module('app',[]);

Step 4

Now to create the controller.

So, here we are reusing the Angular module instance that we initialized already in the app module.

Create a new JavaScript file and name it demoController and add the reference of app.js file to the top.

    /// <reference path="app.js" />

Creating controller

We will now use the registrationModule instance from the app.js file.

Use the following code to create a new controller.

  1. registrationModule.controller("demoController", function ($scope){  
  2.    $scope.Names = [];  
  3.    $scope.Names = loadAllStudentsRecords();  
  4.    function loadAllStudentsRecords(){  
  5.       var names=[“Aravind”,”Siddharth”,”Senthil”,Abhinav”];  
  6.       return names;  
  7.    };  
  8. });  

Here, the Controller name is demoController.

Step 5

Use ng-app to call the app module in the main page.

In the layout.chtml file, add ng-app=”app” to the HTML tag (we actually initialize our app and register the modules on which it depends).

layout

Also add the script file references of the following resources.

  1. <script src="~/Scripts/angular.js"></script>  
  2. <script src="~/Scripts/app/app.js"></script>  
  3. <script src="~/Scripts/app/demoController.js"></script>  

Step 6

Now to bind the data in the view.

Under View, go to Home and select Index, add the HTML code shown in the following image:

HTML code

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <div class="container">  
  6.     <div class="row">  
  7.       <h1> Angular Js Demo - Part 1</h1>  
  8.     </div>  
  9.     <div class="row" ng-controller="demoController">  
  10.         <table>  
  11.             <tr ng-repeat="name in Names">  
  12.                 <td>{{name}}</td>  
  13.             </tr>  
  14.         </table>  
  15.     </div>  
  16. </div>  
Here, I have done the following two things:
  1. Refer to the JavaScript controller file: ng-controller="demoController">.

  2. Bound the data using a scope variable that is being used inside the controller.


Similar Articles