Mastering AngularJS For .NET Developers - Sample Chapter
Mastering AngularJS For .NET Developers - Sample Chapter
Mastering AngularJS For .NET Developers - Sample Chapter
ee
Sa
pl
Chapter 3, AngularJS Scopes, Controllers, and Filters, the goal of this chapter
is to understand AngularJS scope as well as the controller and its use in AngularJS.
We will also cover the built-in filters of AngularJS and show you how to develop
a custom filter.
Chapter 4, Communicating with the Server Using AngularJS, focuses on how
AngularJS communicates with server-side code, such as web API, web services,
or Data Access Layer (DAL). In this chapter, we will discuss how to retrieve data
from the server using $http and $resources. This chapter also talks about the
authentication and security used for a AngularJS application.
Chapter 5, Creating Applications Using AngularJS, Entity Framework, and ASP.NET
Web API, focuses on how to connect to a database using Entity Framework. In this
chapter, we will discuss how to create a web API using ASP.Net and how to consume
through AngularJS.
Chapter 6, Using AngularJS and ASP.NET Web API for CRUD Operations, will
start with web API routing and then focus on how to Create, Read, Update, and
Delete records from a database using the ASP. Net web API and the AngularJS
$http and $resource directives. We will also discuss the difference between $http
and $resource. At the end of this chapter, we will talk about how to secure the
ASP.Net web API.
Chapter 7, Troubleshooting and Best Practices, focuses on troubleshooting
libraries and tools for AngularJS. In this chapter, we will also discuss how
to perform unit testing of the Angular JS application using Jasmine and Karma.
At the end of chapter, we will go through the AngularJS coding best practices.
Appendix, Angular 2.0, introduces us to the Angular 2.0 framework. It may
not be a major update to the previous version, but is a complete rewrite of the
entire framework and includes significant changes. Here, we also talked about
certain Angular 2.0 changes. Angular 2.0 will hopefully be released at the end
of 2015.
Introduction
The goal of this chapter is to understand the need for client-side development and to
understand AngularJS. We will also get acquainted with the anatomy of AngularJS
and its conceptual overview. Finally, we will discuss the basics of a single-page
application development process. This chapter is organized as follows:
Understanding AngularJS
Introduction
In the past, most developers were developing server-side applications because of the
available server-side frameworks. Windows Presentation Foundation (WPF) or web
frameworks, such as ASP.NET or Silverlight, are used to create objects that contain
data and to bind them to user interface controls, such as HTML. However, improved
browser features, faster JavaScript engines, and the increase in the usage of mobile
devices, such as iPad, iPhone, and Android devices, have definitely shifted the
trend from server-side to client-side development. However, data binding has been
difficult in client-side application development because neither HTML nor JavaScript
natively supports data-binding.
It is possible to achieve client-side data binding from scratch; however, it is definitely
challenging and possibly not the best solution available. It is also very difficult
to maintain and reuse the code. To create a client-side application is an amazing
ability although the complexity involved in creating a client-side application is high.
To develop a client-side application means to manipulate the Document Object
Model (DOM) in a browser that runs JavaScript. One of the benefits of client-side
applications is that HTML (DOM) will be updated with the click of a button, rather
than the user waiting for the server to respond. In the case of a server-side rendering,
it is very difficult to update the page. Any portion of a page that's animated or highly
interactive (a draggable slider, sortable table, drop-down menu) almost certainly
uses client-side rendering.
For the past several years, the application development landscape has changed
drastically because of the increase in the use of mobile devices, such as smartphones
and tablets. In 2013, mobile web traffic increased substantially to almost a third
of the total web traffic; this web traffic is expected to increase in the near future.
Applications are expected to be able to work on different platforms such as
Windows, web, and mobile. In order to create multiplatform applications, the
application should support the diversity of client browsers and plugins, such as Java
and Adobe Flash Player. This is because an application becomes problematic if the
plugins are not available or not supported on all devices.
A client-side application development environment enables developers to slowly
and gradually replace applications based on browser plugins with newer versions
of HTML, CSS, and JavaScript applications. While previous development tools
would abstract away the key elements of HTML, CSS, and JavaScript, client-side
development embraces all these tools. Using client-side development, a programmer
can now render and manipulate content by focusing on client-browser capabilities.
Several client-side application development approaches, such as responsive page
design and progressive development are adopted to build modern web applications
that include single-page applications.
[2]
Chapter 1
Description
AngularJS
Backbone.js
Backbone.js follows the MVC design pattern for data binding and
uses key/value binding as well as customer events.
Derby
[3]
Introduction
Library name
Description
Ember
jQXB Expression
Binder
JsViews
KnockoutJS
Meteor
Simpli5
Understanding AngularJS
The popularity of developing client-side applications for mobile devices, such as
iPhones, iPads, and Android tablets is a direct result of market penetration and a
growing user base for these devices. Moreover, JavaScript, the MVC framework,
and other libraries, such as Backbone.js, Node.js, and so on, have been released
and adopted in the mainstream programming. In this section, we will discuss what
AngularJS is and its importance.
What is AngularJS?
AngularJS is a client-side JavaScript library, which has been developed based on the
MVC design pattern. AngularJS is used for client-side data binding of client-centric
applications. It is open source and used by Google Inc. and its Google community.
AngularJS assists to create a client-side application that needs HTML, CSS, and
JavaScript. AngularJS's JavaScript framework is an effort taken to make both
development and testing of application easier.
[4]
Chapter 1
AngularJS contains additional custom HTML tags. It submits the directives in those
custom HTML tags and binds the HTML elements in client side with a model's
data using standard JavaScript. The values of the JavaScript variables can be set or
retrieved dynamically with JSON resources.
The way AngularJS's data binding and dependency injection works is that it helps
to write very less or no code for the client-side binding. AngularJS is a structural
framework for dynamic application development. It lets HTML express an
application's components very clearly and concisely within the browser. AngularJS
proves to be a good candidate to work with the server technology and especially
with ASP.NET and Microsoft's MVC.
These days, AngularJS is popular because it extends HTML with additional elements
to create a template and to enable DOM for one-way or two-way binding. In real
applications, in addition to data binding between view and model, executing the
business logic depends on servers. AngularJS has a very rich, built-in support
to communicate with the server and it also provides a built-in wrapper for
communication with RESTful services.
Why AngularJS?
AngularJS proceeds by minimizing the impedance mismatch between an
application's need for constructing a new HTML and document-centric HTML. Thus,
as compared to other available libraries, it takes a different approach. Directives are
used in AngularJS to convey to the browser how to use a new syntax. Some of the
examples of the directives are:
Data-binding, as in {{}}
[5]
Introduction
AngularJS has been developed in the belief that it can be used to solve problems that
don't require the developer to specify any extra procedures.
The following are the design goals of AngularJS:
Separation of the client side of an application from the server side. This
allows development work to continue in parallel and allows reuse of both the
sides.
Kernel application with directory layout and test scripts as a starting point.
[6]
Chapter 1
[7]
Introduction
All the points up till now mean that you get to write less code. You don't
have to write your own MVC pipeline. The view is defined using HTML,
which is more concise. Data models are simpler to write without getters/
setters. Data-binding means that you don't have to put data into the view
manually. Since directives are separate from the app code, they can be
written by another team in parallel with minimal integration issues. Filters
allow you to manipulate data on the view level without changing your
controllers. Yes, this is sort of a summary bullet point, but writing less code
is a big deal!
Controllers in AngularJS are functions, which are used to govern the scope.
For example, you will use the controller to prefill the data into the scope
from the server or to implement business logic validations. In contrast to
alternative frameworks, controllers are not objects and there is no inheritance
involved. If controllers are easy, then where the work ought to be performed?
AngularJS introduces services to do just that. Services are specifically what
they sound like. They should not get entangled with the MVC of your
application by merely offering associate outward API to reveal no matter
what you wish it to reveal. Most of the time, the service syncs up to a server
to keep up the associate offline data store and exposes ways to push and pull
information to and from a server. AngularJS produces a resource sharing
service that enables multiple controllers to share an equivalent resource.
Services are designed to be standalone objects that cut loose your application.
They permit your controller to stay lean and dedicated to the view and scope
that they are assigned to. Services are mainly used to replace the concept of
class in object-oriented programming. Of course, implementation of services
is not needed and it's utterly acceptable to try and do some lightweight lifting
within your controller to avoid over complexness.
[8]
Chapter 1
[9]
Introduction
Decouple the client side of the associate degree application from the server
side. This permits development work to progress in parallel and permits
recycling of either side.
[ 10 ]
Chapter 1
When we quote views and controllers, their possession itself explains the separation.
The views are simply the presentation type of the associate application; it doesn't
have to be compelled to specifically concerning the requests that return from the
controller. The model is independent of view and controllers; it solely holds the
business entities that will be passed to any view by the controller, as required,
for exposing them to the end user. The controller is independent of views and
models. Its sole purpose is to handle requests and to pass them on as per the routes
outlined and as per the necessity of the rendering views. Therefore, our business
entities (model), business logic (controller), and presentation logic (view) layers are
independent of every alternative.
[ 11 ]
Introduction
Model
The model is where the application's data objects are stored. The model doesn't
apprehend anything regarding views and controllers. Once a model changes, usually
it will give its observers notice that a modification has occurred. A model contains
data that represents this state during the application's lifecycle. The model doesn't
have direct access to the view or controller. Any modification within the model gets
transmitted to the view through the controller. This allows the model to be separated
from the view and controller, which helps reusability and quantifiability of the code.
We will use an identical model to transmit data to totally different views throughout
an application's data request. Views show this data. Controllers manage the link
between your model and your views. Models store data, which is often dynamic data
from a database; otherwise, you can even get data from a static JSON file, which is
the business entity on which the general application operates. Several applications
use a persistent storage mechanism (such as a database) to store data. MVC doesn't
specifically mention the data access layer; as a result, it's encapsulated by the model.
The following is the code example of the JSON data:
$scope.meal= {
'breakfast'
'Lunch'
'Dinner'
}
:
:
:
'Orange Juice',
'Fruit Salad',
'Vegetable Rice'
View
A view is what's bestowed on the users and the way users interact with the
application. The view is formed with HTML, CSS, JavaScript, and other templates.
Views show a model's information by using double curly brackets to bind expressions
to elements, as shown in the following example. A view would get information from
the meal variable that holds the JSON data for breakfast. The code example for view
is as follows:
<h1> {{meal.breakfast}} </h1>
[ 12 ]
Chapter 1
Controller
The controller is the decision maker and also the glue between a model and view.
The controller updates the view when the model changes. Additionally, it adds event
listeners to the view and updates the model when the user manipulates the view.
Controllers can be used to manage a model and data can be retrieved as well as
flaunted to the end user. Wrap the model during a controller function, as shown in
the following example:
var app = angular.module('myApp');
app.controller('ctrlFood', function ($scope) {
}
<div ng-controller = "ctrlFood"></div>
Introduction
An example code for a web page that takes your name and favorite car as input and
then displays it to the reader with a counter for the car is shown as follows:
<html ng-app="myApp">
<head>
<script src="angular.js"></script>
<script src="AngularControllers.js"></script>
</head>
<body>
<h1><u>Mastering AngularJS for .Net Developer</u></h1>
<div ng-controller="myController">
<label>Name:</label>
<inputtype="text"placeholder="Please enter name"ng-model="name">
<h4ng-show="name">Hello! <b>{{name}}</b> select your favorite car
from dropdown</h4>
<selectng-model="selectedCar"ng-change="onCarSelectionChanged()">
<optionvalue="">Please select car</option>
<option>Audi</option>
<option>BMW</option>
<option>Mercedes-Benz</option>
<option>Porsche</option>
<option>Volkswagen</option>
</select>
<h3ng-show="selectedCar">
<span style="font-weight:normal">{{name}} your favorite car is
<b>{{selectedCar}}</b></span>
</h3>
<spanng-show="countCarSelectionChanged> 0">You change your
favorite car {{countCarSelectionChanged}} times.
</span>
</div>
</body>
</html>
[ 14 ]
Chapter 1
Loading index.html into a browser will then produce what you see in the
following screenshot:
[ 15 ]
Introduction
There are no classes or IDs within the markup language to identify where to
connect event listeners.
The myController class has got the $scope object that it needed without
having to create it.
In the preceding code example, to select your favorite car as input in line 1,
AngularJS specifies the distinctive HTML attribute, ng-app. This attribute sets the
boundaries of the application and is applied on any HTML element within that
boundary. The ng-app attribute within the HTML tag is the AngularJS application
root element. AngularJS will parse the markup delimited by the application root
element and look for any ng- prefixed elements, attributes, or CSS classes. It will
match some regular HTML tags, such as input, and select them if they contain the
ng- prefixed attributes or CSS classes. These entities will then be mapped to the
instances of special AngularJS directives.
The directives are accustomed to adding dynamic behavior to HTML content and
introducing a strong, useful, and declarative user interface definition language.
All HTML components in an AngularJS application will be related to at least one
instance of a scope. A scope links the view, by HTML elements to the code behind
the view and during this example by directives. The scope object is initialized and
owned by AngularJS components, and also, the view solely references properties
and functions of the scope object. The applying root elements will be related to the
initial scope of the application. This primary scope is named the root scope, and any
AngularJS application can have a minimum of one scope, which is the instance of the
root scope.
[ 16 ]
Chapter 1
[ 17 ]
Introduction
The ng-show directive is used with a condition. It will show the value of the
countCarSelectionChanged model property if it is greater than 0.
The following figure shows the data flow of the preceding code example:
The ng-init directive assigns a value to the name property on the scope
[ 18 ]
Chapter 1
Description
ng-bind
ng-model
ng-model-options
ng-class
ng-controller
ng-repeat
ng-switch
ng-view
ng-if
[ 19 ]
Introduction
AngularJS is like other libraries in which you can invoke the functions as
you want.
You need to tell AngularJS which part of the DOM it should manage
with ng-app directive. AngularJS can be loaded from Google's
content delivery network (CDN).
It is recommended that you use Google's CDN, as shown in the preceding code,
because Google's servers are fast and the script is cacheable across applications. If
you prefer to host locally, you can do that too. Just specify the correct location in src,
as shown in the following code:
<head>
<script src="~/scripts/angular.min.js"></script>
</head>
It is not required that you use AngularJS on the whole page, it can also be used only
for a specific part of the page. The ng-app directive lets AngularJS know which part of
the HTML (DOM) should be managed. If the whole application is developed by using
AngularJS, then include ng-app in the <html> tag, as shown in the following code:
<htmlng-app>
<head>
<script src="~/scripts/angular.min.js"></script>
</head>
<body>
</body>
</html>
[ 20 ]
Chapter 1
</div>
</body>
</html>
Templates
Templates in AngularJS are HTML files with extra markup. This markup consists
of directives that show how the model ought to be represented in the view.
AngularJS manipulates the DOM and not strings (in distinction to alternative
JavaScript frameworks).
Directives
In AngularJS, the sole place where an application touches the DOM is within its
directives. Directives permit extending markup language; they'll be used to
produce custom HTML tags or to decorate existing ones with new behavior.
Let's create a directive that adds copyright information by using a new
<copyright> tag:
var app = angular.module('app', []);
app.directive('copyright', function(){
return {
restrict: "E",
replace: true,
template: "<p>Copyright 2014</p>"
}
});
[ 21 ]
Introduction
restrict: 'E': This means we should use an HTML tag to reference it,
that is <copyright>
The following code uses the HTML tag to reference the directive:
<body ng-app="app" >
<copyright>
</copyright>
</body>
Filters
An AngularJS filter is accustomed to remodel data. A filter is added to expressions
and directives that employ a pipe character. You would also use filters in controllers,
services, and directives. You can also create your own filters, which will be discussed
in detail in Chapter 3, AngularJS Scopes, Controllers, and Filters, as shown:
<input ng-model="value" type="text" placeholder="Try to enter a number
with 3 or more decimal places...">
<h1>{{value | number:2}}</h1>
The filter used in the expression here, {{value | number:2}}, will only display a
value of up to two decimal places. To implement a filter, the pipe symbol | is used
after the variable, value.
[ 22 ]
Chapter 1
Services
Services are meant to share data between controllers. In other words, they supply a
centralized purpose of giving access to the data. The aim of an AngularJS service is
to come up with one object or function that represents the service to the remainder of
the application.
In the following code example, a service is shared between two controllers. In this
way, each controller will access and manipulate the data that was entered within the
input managed by the other controller:
var app = angular.module('app', []);
app.service('MessageService', function () {
this.payload = { message: 'Hello from a Service' };
});
app.controller('FirstController', function ($scope, MessageService) {
$scope.payload = MessageService.payload;
});
app.controller('SecondController', function ($scope, MessageService) {
$scope.payload = MessageService.payload;
});
[ 23 ]
Introduction
In the preceding code and following diagram, the application contains two
controllers, FirstController and SecondController. Each of these controllers
requires certain user data. Thus, instead of repeating the logic to fetch data in
each controller, we will create a user service, which will hide the complexity.
AngularJS automatically injects the user service in both, FirstController and
SecondController. Therefore, our application becomes modular and testable. The
following figure depicts the user services:
Description
$resource
$document
$window
$timeout
$parse
$cacheFactory
$filter
[ 24 ]
Chapter 1
Dependency Injection
Dependency Injection is a software system pattern, which means that if an object
needs another object (a dependency), this dependency will be passed to that object
rather than it being made (for example, initialized) by that object. Imagine it in the
following manner: you define what objects you wish for and they are able to work
for you right away. It makes the application easier to develop, as shown in the
following code:
functionUserController($scope) {
$scope.currentUser = {
firstName: 'John',
lastName: 'Doe'
};
}
In the preceding code snippet, $scope gets injected by AngularJS whenever this
controller is instantiated.
The compiler
After AngularJS finds the ng-app directive, it'll create a new $rootScope and then
compile the child DOM components of the root node. To compile an HTML (DOM)
element, we are compelled to use the $compile service. However, AngularJS has
the capability to handle it, and $compile takes a markup or jQuery object and
returns a linking function that is then known as the scope for it to bind to. Once the
linking function is called, it returns an angular component that has the practicality
of a jQuery object. However, it conjointly contains a scope and numerous different
angular-specific data. Before, or once the compilation is complete, the following
components are often inserted in the page:
Compile: This component traverse the DOM and collect all the directives.
Link: This component mix the directives with a scope and turn out a live
view. Any changes within the scope model are reflected within the view, and
any user interactions with the view are mirrored within the scope model.
This makes the scope model the single supply of truth.
[ 25 ]
Introduction
Some directives such as ng-repeat clones DOM components once for every item
in a very assortment. Having a compile and link part improves performance since
the cloned guide solely has to be compiled once and then linked once for every
clone instance.
The $compile perform traverses the DOM and appears for the directives. For every
directive it finds, it adds that directive to a list of directives. Once the complete
DOM is traversed, it will arrange that list of directives according to their priority.
Then, every directive's own compile perform is dead, which gives every directive
the possibility to change the DOM itself. Every compile perform returns a linking
perform, which is then composed into a "combined" linking function and is returned.
AngularJS executes the linking performance and ensures to pass it within the scope
that we wish to bind it to within this method. This can run all the linking functions
that bind the same scope or bet on the directive to produce new scopes. Once all
the linking functions are dead, the combined linking perform returns a collection of
DOM elements complete with data-bindings and event listeners that AngularJS can
append to the parent node.
[ 26 ]
Chapter 1
AngularJS can be an excellent SPA framework, but it's not used only for that. You
don't have to load these dynamic views with it. In truth, you may simply use it to
achieve separation of code.
The challenge of building SPAs from scratch is that there are lots of various problems
to deal with that are related to DOM manipulation and history. However, you can
dynamically load modules, and the way you load these modules guarantees that you
create sync calls and so on. Routing becomes a large issue as a result of which you
have to possess a way to trace "Where are we tending towards? And wherever are
we going?" All of these constraint are made into AngularJS.
As mentioned, AngularJS is a full-featured SPA framework. We have two-way databinding and we tend to have the Model-View-Controller structure. Routing of views,
which we discussed in the earlier section, into the shell pages is finished through
built-in routing support. Testing was designed right from the start; thus, you will be
able to build strong tests if required. For DOM manipulation, jQLite is built in, which
is like the Mini-Me of jQuery. If you wish to use more advanced stuff, you'll be able
to even use jQuery. AngularJS and jQuery play really nicely together.
Benefits of SPAs
The benefits of SPAs are as follows:
By using the responsive web design, so it's very well supported on all devices
with different resolutions and screen sizes
A page is not refreshed on every request; only part of it is, which gives the
user a better experience
SPAs maintain navigation and history of pages that are loaded, which makes
it faster
Summary
This chapter introduced the requirement for client-side development and helped you
understand the basics of AngularJS. The client-side development enables application
developers to develop applications that are based on browser plugins with newer
versions of HTML, CSS, and JavaScript. The major advantage of using client-side
development is that it takes less time than other forms of application development
processes due to its inherent ability to update whenever the user clicks. AngularJS
is a Google-owned open source application framework that can be used to create
single-page web applications by employing the same elements that are used in
client-side development.
[ 27 ]
Introduction
We also looked at the anatomy of AngularJS and dealt with the MVC structure.
MVC can be incorporated in AngularJS to provide a better Model-View-Controller
capability. This approach is becoming more and more popular due to its distinct
features of managing its data, application logic, and presenting data to the viewer
through using client-side development.
Finally, we mentioned the fundamentals of a single-page application development
method. A single-page application uses the application's server side for its first
rendering, after which it relies exclusively on the client side. This enables the
developer to use several static web pages and then link them together.
In the next chapter, we will explore the AngularJS bindings and directives.
[ 28 ]
www.PacktPub.com
Stay Connected: