AngularJS

Introduction to AngularJS

A computer language is an electronic language that gives instruction to a computer to perform one or more operations. Like a human language, a computer…

9 min read1,998 words19 code samples

Fundamentals of AngularJS#

Introduction to Computer Languages#

Electronic instructions known as computer languages are used to direct a computer's actions across various operations. Similar to human speech, these languages utilize specific symbols and vocabulary while adhering to established rules to form logical, understandable expressions. C stands as a foundational language, primarily employed for building diverse software types and supported by nearly every operating system. Due to its robustness and essential features, it served as the basis for developing other languages like C++, Java, and C#.

Introduction to JavaScript#

To make it possible to perform interactive operations on a webpage, a language named JavaScript was created. It is primarily based on the C language and its ways of doing things. JavaScript is a computer language used to create webpages on which a visitor can create values to be submitted to a webserver. The webserver can then react and send a response to the visitor. This means that JavaScript is used to create interactive webpages. To enhance JavaScript functionality, a library named AngularJS was created. AngularJS can be used to perform various types of operations for the webcontrols of an HTML webpage.

An AngularJS Project#

To use the functionalities of AngularJS, you can create a website that contains one or more webpages. In a webpage, you will add AngularJS code. You can use any text editor such as Notepad to write your code. For our lessons, we will use Microsoft Visual Studio. It is free. You can download it from the Microsoft website such as asp.net and install it in your computer. Practical Learning: Introducing AngularJS

  1. Start Microsoft Visual Studio
  2. To create a new website, on the main menu, click File -> New -> Project ...
  3. In the New Project dialog box, in the left frame, under Visual C#, click Web
  4. In the middle frame, click ASP.NET Web Application (.NET Framework)
  5. Change the project Name to Exercise1
  6. Press Enter
  7. In the New ASP.NET Wep Application dialog box, click the MVC icon
  8. Click OK

Using AngularJS#

Your webpage must be configured to recognize AngularJS before you can utilize its features. Since browsers do not come with AngularJS pre-installed, you must provide a reference to it. Several methods are available for this. You can obtain the library directly from the official website at https://angularjs.org/ and save the file to your local machine. To integrate it into an ASP.NET MVC project, you need to add the library manually. After downloading the file, go to Microsoft Visual Studio and use the Solution Explorer to right-click the Scripts folder, then select Add and choose Existing Item... to pick the file. Alternatively, you can manage the library through NuGet by right-clicking your project in Solution Explorer, selecting Manage NuGet Packages..., searching for angularjs in the Browse tab, and selecting it from the results.

In the middle-right frame, click Install. If a dialog box comes up, read it and click OK:

After adding the AngularJS library to your project, after starting a webpage, one technique is to add a link of either the AngularJS URL or a link to the file you downloaded. The link is created as done for an external JavaScript document. Here is an example:

C#
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
</head>

</body>
</html>

Practical Learning: Installing AngularJS

  1. In the Solution Explorer, right-click Exercise1 and click Manage NuGet Packages...
  2. Click the Browser button. Do a search on AngularJS (you must be connected to the Internet)
  3. In the list, click angularjs:
  4. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK In the Solution Explorer, expand Scripts and notice the angular files

AngularJS and ASP.NET Projects#

As an alternative, if you create an ASP.NET (MVC, Web API, etc) project in Microsoft Visual Studio, the studio creates a file named BundleConfig.cs. That file contains a class of the same name. That class contains a static method named RegisterBundles. In that method, the BundleCollection class is used to create a list of the libraries and CSS formats that your project needs. In the RegisterBundles() method of the class, you can add a reference to the AngularJS library to that method. Practical Learning: Adding an AngularJS Reference

  1. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  2. Add a reference to the AngularJS as follows: using System.Web; using System.Web.Optimization; namespace Exercise1 { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js" , "~/Scripts/angular.js" )); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
  3. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  4. In the class, add a method as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Exercise1.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Exercise() { return View(); } } }
  5. Right-click the public ActionResult Exercise() line and click Add View...
  6. In the Add View dialog box, make sure the View Name text box is displaying Exercise. Click Add

Accessing AngularJS in a Web Page#

When creating a webpage, if you are connected to the Interrnet, you can add a direct link to the AngularJS library, which is:

C#
https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js

To access AngularJS in an ASP.NET view, call the Render() method of the Scripts class and pass the path to the jQuery library. Practical Learning: Accessing AngularJS in a Web Page

  1. Change the document as follows: @{ ViewBag.Title = "Exercise"; } <h2>Exercise</h2> @Scripts.Render("~/bundles/jquery")
  2. Press Ctrl + F5 to execute
  3. Close the browser and return to your programming environment

Introduction to AngularJS Directives#

Overview#

To let you control the value or meaning of an HTML tag, AngularJS lets you add an attribute to the tag. Such a special attribute is named a directive. AngularJS provides various directives, for different goals. A directive is primarily recognized by its name. The name of a tag starts with ng-. The formula to apply a directive to an HTML tag is:

C#
<web-tag ng-directive-name="directive-value"></web-tag>

Because directives play different roles, an HTML tag can have more than one directive:

C#
<web-tag ng-directive1-name="directive1-value"
		 ng-directive2-name="directive2-value"
         . . .
         ng-directive_n-name="directive_n-value"></web-tag>

Some directives are used more regularly than others. Of course, this depends on what you are trying to do.

The Angular Application Directive#

Before applying AngularJS's influence to your webpage, you must indicate the area or section that will use it. You have many options. The directive that marks the AngularJS sphere of influence is named ng-app.

AngularJS for a Web Page#

If you want a whole webpage to accept AngularJS, in the <HTML> tag of the webpage, add the ng-app attribute. Here is an example:

C#
<html ng-app>
<head>
<title>Exercise</title>
</head>
<body>
<p>Exercise</p>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
</body>
</html>

AngularJS in a Body#

If you want the use AngularJS in only the body section, add this attribute to the <BODY> tag. Here is an example:

C#
<html>
<head>
<title>Exercise</title>
</head>
<body ng-app>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
<p>Exercise</p>
</body>
</html>

AngularJS for a Form#

Instead of covering the whole webpage, you can delimit a specific area where you want to use AngularJS. In this case, you can use or create a tag somewhere inside the webpage. If you are creating a form, you can add the attribute to your <FORM> tag.

AngularJS for a Section#

You can delimit the influence of AngularJS code to a section. In this case, you can apply the ng-app directive to an HTML tag that is usually used as a container. Examples of such tags <HEADER>, <SECTION>, <FIELDSET>, <FOOTER>, etc. Here is an example:

C#
. . .

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>

<h2>Exercise</h2>

<section ng-app>

</section>

. . .

AngularJS for an Anonymous Section#

If you don't a specific section in which you want to include your AngularJS sphere of influence, probably the easiest thing to do is to create a <DIV> section and simply add the ng-app directive to it.

AngularJS in a Rendered Body#

When you create an ASP.NET MVC in Microsoft Visual Studio, the studio creates many files. One of them is named _Layout.cshtml. That file is central to the other webpages (views) your will create. In fact, that file will act as a container to the other webpages. That file creates a section that will display the other webpages. To make this happen, the _Layout.cshtml document contains a line as @RenderBody(). This means that the _Layout.cshtml document calls the @RenderBody() method. On an ASP.NET MVC project, if you want to apply AngularJS to a central webpage, you can apply the ng-app directive to one of the containing tags. This can be the <HTML> tag. Here is an example:

C#
<!DOCTYPE html>
<html ng-app>
<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>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        . . .
    </div>
    <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")
    @RenderSection("scripts", required: false)
</body>
</html>

You can also apply the directive to the <BODY> tag of the _Layout.cshtml document. Here is an example:

C#
<!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>
<body ng-app>
    <div class="navbar navbar-inverse navbar-fixed-top">
        . . .
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    . . .
</body>
</html>

You can also apply the attribute to the DIV tag that surrounds the @RenderBody() call. Here is an example:

C#
<!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>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content" ng-app>
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

You can also create your own section that surrounds the @RenderBody() call. Here is an example:

C#
<!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>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        <div ng-app>
            @RenderBody()
        </div>
        
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

A Modeled Directive#

Inside the sphere of influence of a tag marked with the ng-app attribute, you can add any regular HTML (and CSS of course) code, which would be made of tags. If you want to influence the value of a Web control using AngularJS, you must mark such a tag. To support this, AngularJS provides a directive named ng-model. To use it, add it as an attribute to the desired tag of a Web control but give it the name you would give to its HTML ID or NAME attribute. Here are examples:

C#
. . .

<h2>Exercise</h2>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>

<div ng-app>
        <table>
            <tr>
                <td>First Name:</td>
                <td><input type="text" ng-model="firstName" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" ng-model="lastName" /></td>
            </tr>
        </table>   
</div>

. . .

Binding an HTML Tag#

AngularJS allows you to influence the behavior of an HTML tag using code. To make this possible, the library provides a directive named ng-bind. To use it, add it as an attribute to an HTML tag. Assign an ID or NAME type of name to it. Here is an example:

C#
. . .

<h2>Exercise</h2>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>

<div ng-app>
    <table>
        <tr>
            <td>First Name:</td>
            <td><input type="text"ng-model="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><input type="text" ng-model="lastName" /></td>
        </tr>
    </table>
        
    <p ng-bind="biography"></p>    
</div>

. . .

Introduction to AngularJS Declaratives#

A Placeholder for a Value#

You can create a unique placeholder in AngularJS to show specific values. These are defined by starting with {{ and ending with }}. Inside a {{}} placeholder, you can place a constant, such as {{22}}, which will display that exact value when the page loads. Alternatively, you can insert a name within the brackets to represent that section. See the example below:

C#
. . .

<h2>Exercise</h2>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>

<div ng-app>
	<p>{{dateHired}}</p>    
</div>

. . .

Depending on what you are trying to do, you can include more than one name in the placeholder.

Binding Data to an HTML Tag#

Binding an HTML control to a placeholder is equivalent to making sure that the placeholder receives the value given to the HTML control. This is done by using the ng-model on a control and a {{}} placeholder outside the control. The name in the {{}} placeholder, or one of the names in {{}}, should (must) be an ng-model name given to one of the controls on the document. Here are examples:

C#
. . .

<h2>Exercise</h2>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>

<div ng-app>
    <table>
        <tr>
            <td>First Name:</td>
            <td><input type="text" ng-model="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><input type="text" ng-model="lastName" /></td>
        </tr>
    </table>
        
    <p>{{lastName}}, {{firstName}}</p>    
</div>

. . .

In this example, when the value of the firstName text box changes, the value in the {{firstName}} becomes the same. The lastName items follow the same logic.

The Value of a Web Control#

As you are probably aware, most webcontrols display or hold a value, particularly the text box. AngularJS allows you to automatically specify the value of a control that depends on (an)other control(s). To make this happen, add a VALUE attribute to the control. For its value, create a {{}} placeholder. This would be done as <input type="text" value="{{FirstName}}" />. You can also add as many {{}} placeholder as you need. Here is an example:

C#
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<style>
.whole-page {
    margin: auto;
    width:  400px;
}
</style>
<script src="angular.js"></script>
</head>
<body ng-app>
<div class="whole-page">
    <h1>Employment Application</h1>
    
    <form name="EmploymentApplication" method="post">
        <table>
            <tr>
                <td style="width: 100px; font-weight: bold">First Name:</td>
                <td><input type="text" ng-model="FirstName" /></td>
            </tr>
            <tr>
                <td style="font-weight: bold">Last Name:</td>
                <td><input type="text" ng-model="LastName" /></td>
            </tr>
            <tr>
                <td style="font-weight: bold">Full Name:</td>
                <td><input type="text" value="{{FirstName}} {{LastName}}" /></td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

To let you create a link in a {{}} placeholder, AngularJS provides the ng-href directive. You can use it in place of the HREF attribute of the A element. Its value must be specified as a string:

C#
<a ng-href="{{'link-address'}}">link-text</a>

To indicate the root address of your project, enter localhost and the port number. Here is an example:

C#
<p><a ng-href="{{'http://localhost:59148/'}}">Water Distribution Company - Home</a></p>

You can also provide the absolute or the relative address of a webpage. Here is an example:

C#
<p><a ng-href="{{'Country/State/Index.html'}}">State Institutions</a></p>

Practical Learning: Ending the Lesson

  • Close Microsoft Visual Studio

Home Copyright © 2001-2019, C# Key Next