Monday, 9 May 2016

How to setup Angular js in MVC 5 application

1 comment
angular js logo

Introduction:

Hi every one welcome again.In this tutorial i am going to explain how to setup and use Angular js in MVC 5 application.from now on wards we are going to learn about Angular js in step by step.I will cover all the topic and sample projects using angular js with MVC 5.

What is Angular JS

Angular JS is an open-source web application framework, maintained by Google and the community, that assists with creating single-page applications. Angular JS supports MVC style of application design and its primarily aimed to develop SPA(Single Page Applications). Its also support two-way binding that means your data model and control’s data will be in sync.

Form here i am going to cover angular js modules step by step from beginning to advanced level with client side using Angular js and server side using ASP.NET MVC 5.
In this tutorial we are going to learn How to setup angular js in MVC 5 application 
Please refer Introducton to Angular here explained more about angular .

Step 1: Create New MVC project

1.Go to File Menu -->New --> Project --> Select ASP.NET web application --> Enter name of application -->Choose MVC template -->Click Ok.

Step 2: Add Angular js library to project

1.You can download angular from here. or
2.You can add from Nuget Package Manager


installing angular in mvc5

3.Install Both Angular JS Core and Route files.

Step 3: Add a bundle for Angular JS library

1.Go to Solution explorer --> App_Start --> open BundleConfig.cs -->add below code there.
//Angular js bundles
      bundles.Add(new ScriptBundle("~/bundles/angular").Include(
             "~/Scripts/angular.js",
            "~/Scripts/angular-route.js"));

Step 4: Modify _Layout Pages to add Anjular

1.Replace the _Layout page with below code
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
@*
    ng-app initilizes the angular js application(Auto bootstraps)
    ng-app also tells to angular js that this <body> element-
     -is owner of created angular js application
*@
<body ng-app="myapplication">
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @*Angular js library files*@
    @Scripts.Render("~/bundles/angular")
    <script src="~/Scripts/myscript.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

Here "ng-app" directive is used to initialize the Angular application(auto-bootstrap angular application). And here we specified that <body ng-app="myapplication"> so, <div> element is owner for angular application created.

Step 5: Add Script file to create Module and Controller

1.Right click Scripts --> Add --> Java script file --> name it as myscript.js 
2.Add below code to create angular module and Controller
    var app;
    (function () {
    //creating module in angular
    app = angular.module("myapplication", ['ngRoute']);//it uses the ngRoute if we implement routing

    //creating controller on angular
    //here $scope object is used to share data between Controller and view.

    app.controller("HomeController", function ($scope) {
        $scope.Message = "Welcome to Angular js buddy!";
        //$scope.Message = "Hi this is Two";
    })
})();
Here i added an angular $scope object to controller.

angular.module: An angular module is a collection of Controllers,Services,filters and directives etc.Module is an starting point of the Angular application. It initializes the Controllers,Services,filters at the time application is booted.Simply it is like staring point like Main() method in C# language.

angular.Controller: It contains the front end business logic like Controller in MVC application.It contains methods and variables that are used in View. Controllers also initializes $scope object.

$scope: It is a simple object.It uses angular js two way data binding to bind the controllers model data to view.$scope object is automatically created and injected using dependebcy injection when controller was intialized in angular application.

Step 6: Add Controller

1.Right click Controllers --> Add -->Controller --> Select Empty Controller --> name it HomeController.cs.
2.Then add Index Action to Controller class.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AngularSampleApp.Controllers
{
    public class HomeController : Controller
    {
        //Index action
        public ActionResult Index()
        {
            return View();
        }
    }
}

Step 7: Add Index View to Action

1.Right click on Index action --> Add View -->Select Empty view template --> Click Add.
2.Replace it with below code.
Index.cshtml:
@{
    ViewBag.Title = "Index page";
}
<h2 class="text-info">Angular introdution</h2>

<div ng-controller="HomeController">
    {{Message}}

</div>

Here ng-controller directive specifies which controller in charge of this View.
Here, The scope of $scope object in Angular js application.

ng-controller: The ng-controller directive attaches controller to view.By using ng-controller we can attach multiple controllers to a single view.We can also attach a controller object to DOM element using ng-controller directive like above <div > element.
when a controller attached to a DOM element a new $scope object also attached to that DOM element.

Now run application

first angular application

Here, "Welcome to Angular js buddy!" text is specified in mycontroller .see code in step 5.
Download code for this here.
You may also like below
How to get data from server using Angular 

Conclusion: I hope you understand my tutorial well.We will going to learn more concepts in future tutorials.


1 comment:

  1. Nice Tutorial but, the tutorial wouldn't work for few reasons as in, You cannot wrap "var app=" the module definition inside "$(function", since it waits for DOM to load. Secondly, I was forced to move all the scripts above the body, since it was expecting controller when initialized and was throwing error. I created same replica of this tutorial and I faced these problems. No offense, but just an information.

    ReplyDelete