35
Free Sample

Mastering AngularJS for .NET Developers - Sample Chapter

Embed Size (px)

DESCRIPTION

Chapter No. 1 IntroductionMaster the art of developing applications using AngularJS, ASP.NET Web API 2, and Visual Studio 2013 For more information: http://bit.ly/1EHvrGu

Citation preview

Free Sample

In this package, you will find: • The authors biography • A preview chapter from the book, Chapter 1 'Introduction' • A synopsis of the book’s content • More information on Mastering AngularJS for .NET Developers

About the Authors Mohammad Wadood Majid has been working in the field of application development and design for more than a decade for some major companies in the USA. During this time, he has worked independently as well as with teams to develop a number of highly successful enterprise applications for the Web and mobiles. He is experienced in the development, designing, testing, modification, and maintenance of enterprise applications. Currently, he is working as an enterprise application administrator and developer and a part-time assistant professor at the University of Toledo.

He has worked extensively with MVC, web APIs, ASP.NET, ADO.NET, C#, OData, and RESTful. He has expertise in native mobile apps and web- based application development that can be performed using HTML5, JavaScript, jQuery, Bootstrap, AngularJS, and CSS.

He has experience of working with databases such as SQL Server 2012 and Oracle 11g.

He has also performed research on the following topics:

• Parallel implementation of algorithms on multicore and NVIDIA's GPU • Parallel computation of moving target detection and recognition from

a set of radar signals • Development of parallel programs using multicore and NVIDIA's GPU

for artificial intelligent algorithms, such as evolutionary neural networks and genetic algorithms

Golrokh Mirzaei has several years of software development experience in the software industry and is currently working as a faculty at the Ohio State University. His research involves the development of software applications and multisensor data fusion approach to monitor biological targets using three different sensors: infrared camera (IR), radar, and acoustics. The infrared camera and radar sensors involve video and image processing techniques, including object detection and recognition, feature extraction, classification/clustering, and tracking. He has published several papers at professional IEEE conferences and received several awards. His developments in the field of image processing and computer vision are unique, related to multifidelity, and multidisciplinary. He has also performed research on the following topics:

• Pattern recognition (object detection, feature extraction, tracking, and so on) • Machine learning (supervised/unsupervised learning) • Classification/clustering • Image/video/audio processing (infrared camera, radar, and acoustics) • Bio-inspired computing (ACA, ACO, and GA) • Bayesian inference and fuzzy reasoning

Mastering AngularJS for .NET Developers Application development is a broad term; it can range from developing the simplest static page of plain text to the most complex database-driven, electronic business, and social networking applications. A more comprehensive list of tasks that application development commonly refers to may include, web designing, content development, client relationships, client-side and server-side configurations, and deployments.

In the past, most developers developed server-side applications because of an available server-side framework called Windows Presentation Foundation (WPF) or web frameworks such as ASP.NET or Silverlight. These are used to create objects containing data and bind them to user interface controls such as HTML. However, improved browser features, faster JavaScript engines, and an increase in the usage of mobile devices, such as iPads, iPhones, and Android tablets have definitely shifted the trend from server-side to client-side development. However, data binding has been difficult to implement into client-side application development because neither HTML nor JavaScript natively support it.

It is possible to start client-side data binding from scratch; but, 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 it is high. To develop a client- side application involves manipulating the Document Object Model (DOM) in a browser running JavaScript. One of the benefits of client-side applications is that HTML (DOM) will be updated with the click of a button, rather than keeping a user waiting for the server to respond. In the case of server-side rendering, it is very difficult to update the portion of the page. Any portion of a page that's animated or highly interactive (such as a draggable slider, sortable table, or a drop-down menu) almost certainly uses client-side rendering.

For the last several years, the application development landscape has changed drastically because of an increase in the use of mobile devices, such as smartphones and tablets. In 2013, mobile web traffic had increased substantially to almost a third of the total web traffic; and it's expected is to increase in the near future. Applications are expected to be able to work on different platforms, such as Windows, web, and mobiles. In order to create multiplatform applications; an application should be enabled to support diverse client browsers and plugins, such as Java and Adobe Flash. The application becomes problematic if the plugins are not available or aren't supported on all devices.

Client-side application development environments enable developers to slowly and gradually replace applications, which are based on browser plugins with newer versions of HTML, CSS, and JavaScript. While previous development tools would abstract away the key elements of HTML, CSS, and JavaScript, client-side development developed 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. The development process of these type of applications is, however, challenging and costly when compared to other applications, because they need rapid prototyping, rich client features, and a large JavaScript base to be employed. Another JavaScript framework that has been developed in the same time frame is the AngularJS framework by Google.

There are many libraries that have been introduced, such as QUnit in 2008, Jasmine in 2010, and Backbone and Knockout.js in 2010. These libraries address challenges that involve solving client-rich features. They use derivatives involved in a design pattern, such as Model-View-Controller (MVC), which is common in both server and client-sides. During the design, application data and business logic need to be clearly differentiated. This differentiation is achievable by MVC patterns, and the controller components sit in the middle. The controller has access to all the different elements of the application, thus passing the data to and from the model, updating the view, or responding to view changes that are passed to the model. There are several advantages of using an MVC design pattern; these include reusing code in a better manner (the same model can be used for multiple views), testability (the controller can be tested from a view), and efficient development workflows that are achieved due to the designer's ability to modify the view.

AngularJS can enhance and extend HTML by adding new elements to it and it is based on the MVC pattern. It can also be tested from the start using modular, composable code units. AngularJS has only grown in popularity since its introduction in 2012.

What This Book Covers Chapter 1, Introduction, acquaints you to understanding the need for client- side development and also to AngularJS. You 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.

Chapter 2, Learning AngularJS Binding and Directives, focuses on showing you how the AngularJS data binding works. You will also learn about the use and development of AngularJS directives through code examples.

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.

IntroductionThe 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 the need for client-side development• Understanding AngularJS• Getting acquainted with the anatomy of AngularJS• The conceptual overview of AngularJS• Learning the basics of a single-page application

Understanding the need for client-side developmentApplication development is a broad term; it can range from developing a simple, static page of plain text to developing the most complex database driven electronic businesses and social network applications. A more comprehensive list of tasks, which application development commonly refers to, may include web designing, content development, client relationship, client-side confi guration, server-side confi guration, and deployment.

Introduction

[ 2 ]

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 defi nitely shifted the trend from server-side to client-side development. However, data binding has been diffi cult 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 defi nitely challenging and possibly not the best solution available. It is also very diffi cult 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 benefi ts 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 diffi cult 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 traffi c increased substantially to almost a third of the total web traffi c; this web traffi c 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.

Chapter 1

[ 3 ]

The development process of these types of applications is however challenging and costly when compared to other applications because these applications need rapid prototyping, rich client features, and a large JavaScript base for them to be employed. Another JavaScript framework that has been developed in the same timeframe and is widely used for developing single-page applications is the AngularJS framework by Google.

There are many libraries that have been introduced, such as QUnit in 2008, Jasmine in 2010, and Backbone.js and Knockout.js in 2010. These libraries address the challenges that are involved in solving the rich client features. These libraries use derivatives for a design pattern, such as Model-View-Controller (MVC), which is common in both server-side and client-side. During the design, application data and business logic need to be clearly differentiated. This differentiation is achievable by MVC patterns where the controller components sit in the middle. The controller has access to all the different elements of the application; thus, it passes the data to and from the model, updates the view, or responds to view or changes that are passed to the model. There are several advantages of using the MVC design pattern, such as better code reuse (same model can be used for multiple views), testability (controller can be tested from view), and effi cient development workfl ow that is achieved due to the designer's ability to modify the view.

AngularJS can enhance and extend HTML by adding new elements to it and AngularJS is based on the MVC pattern. It can also be tested from the start using modular, composable code units. AngularJS has grown in popularity since its introduction in 2012.

Client-side data binding librariesThe use of client-side data binding is becoming more widespread as more and more developers are writing client-side applications. Most of these libraries follow the MVC or Model-View-ViewModel (MVVM) design pattern and some of these libraries directly integrate with the server framework, such as Knockout.js.

The following table illustrates the list of a few client-side data binding libraries that can be used for a client-side application development:

Library name DescriptionAngularJS AngularJS uses the MVC and MVVM design pattern.Backbone.js Backbone.js follows the MVC design pattern for data binding and

uses key/value binding as well as customer events.Derby Derby provides a framework that runs in the browser and supports

data binding and templates.

Introduction

[ 4 ]

Library name DescriptionEmber Ember uses templates that update the DOM automatically as the

data changes.jQXB Expression Binder

jQXB Expression Binder is a jQuery plugin that supports two-way data binding and it is very lightweight.

JsViews JsViews is a data binding framework that binds views through the JsRender template.

KnockoutJS KnockoutJS uses the MVVM design pattern and directly integrates with the server framework.

Meteor The Meteor framework uses Node.js on server side and supports data-binding on client side.

Simpli5 Simpli5 is a JavaScript framework that provides support for two-way data-binding.

Nowadays, the cross-platform application development that uses the client-side binding is more popular. Most of the client-side script libraries retrieved from the server using the JavaScript Object Notation (JSON) format and dynamic binding of the HTML elements can be achieved by employing the JSON format. This is because JSON uses multiple client-side libraries and it is an advanced subset of JavaScript itself. JSON is a preferred client-side application format that parses and transmits data using a lightweight framework, making reading and writing of data easier.

Understanding AngularJSThe 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.

Chapter 1

[ 5 ]

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 {{}}• The two-way binding facility in AngularJS enables automatic change of

either the target or source property in case one of them changes• Control structures for repeating and hiding a certain portion of a page• AngularJS sustains the client-side form validation• AngularJS connects the server-side code to DOM elements using JSON• AngularJS provides a way to group HTML to reusable components• AngularJS contains the Hypertext Transfer Protocol service, which can be

used to communicate with remote servers

Introduction

[ 6 ]

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:

• To separate DOM operations from the application logic. This dramatically improves the testability of the code.

• Application testing is of equal importance to application writing. Testing is diffi cult and dramatically affects the way the code is structured.

• 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.

• During the entire lifecycle of building a client-side application, the AngularJS framework helps developers to create a user interface (UI), write business rules, debug, and test the applications.

In developing client-side applications, AngularJS is not a single piece in the overall package of the AngularJS framework. AngularJS puts the DOM and AJAX code in a well-defi ned structure. This makes AngularJS opinionated about how a CRUD application should be built. AngularJS has the following features and advantages:

• Implement the CRUD operation, data-binding, basic directives, form validation, routing, deep-linking, reusable components, and dependency injection.

• Application testing, such as unit-testing, end-to-end testing, mocks, and test harnesses.

• Kernel application with directory layout and test scripts as a starting point.• The AngularJS framework is developed based on the MVC design pattern. It

manages these components and connects them to server.• AngularJS uses additional HTML tags to create a user interface for

applications. It is much easier, more natural, and less complex than creating a user interface using JavaScript. Creating a user interface with AngularJS within HTML is easy to organize; special tags in the DOM determine which controllers to use for each element. The new tags regulate what should be loaded. AngularJS directives make client-side application development easier because in AngularJS, what you see is what you get. So, instead of wasting time thinking and deciding what has to be done, one can just use the AngularJS framework to simply defi ne what you want and what dependencies are involved.

Chapter 1

[ 7 ]

• The AngularJS framework uses Plain Old JavaScript Objects (POJO). Therefore, AngularJS does not need the getter or setter functions. We can directly add properties and loops into the objects. The code looks much cleaner and more organized. The traditional data model is responsible for data determination and server synchronization. AngularJS uses the data model, which uses plain objects; these objects behave like temporary storage areas to store and retrieve data. AngularJS's data model works very closely with controller and view and is known as scope. All the properties of the scope object are automatically bound to the calling view of the scope. AngularJS keeps track of the changes made to these properties and updates the view automatically when needed. There is no data in the scope, which depends on the controller to feed the data into the scope, according to the business logic.

• The AngularJS framework brings additional functionality to the DOM by introducing supplementary tags to HTML, which are known as directives. Directives empower us to invent our own HTML tags. The MVC application can be separated by putting all DOM manipulations into the directives. This separation will permit the MVC application to only focus on updating view with new data. Directives come in the form of custom HTML tags, such as:<myticker></myticker> <!--<!--<!-- <!--custom attributes - -><div data-myticker</div> <!--<!--<!-- <!--customer class names - -><div class="myticker"></div> <!--<!--<!-- <!--used like regular HTML elements - ->

• Directives are designed to be standalone reusable elements separate from the application. In fact, if a particular element is adopted by the HTML5 standard, it should be as simple as removing the custom directive. The application should behave in exactly the same manner without needing to change the application. The controller should not manipulate the DOM directly. All DOM manipulations should be performed by directives.

Introduction

[ 8 ]

• The AngularJS framework provides out-of-the-box fi lter functions. A fi lter is a separate function like the directive. A fi lter will fi lter the data before the data is bound to the view. It is capable of creating a sortable HTML table without writing any JavaScript. In an application, different fi lters can be applied, such as "currency," which will convert a number into the currency format, "lowercase," which will convert the string to lowercase, "orderBy," which will order the list of items in the ascending or descending fi lter, and much more. We can also create a custom fi lter instead of using the out-of-the-box fi lter.

• 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 defi ned 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 prefi ll 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 specifi cally 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 offl ine 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.

Chapter 1

[ 9 ]

• A PubSub system is a pretty common tool that permits decoupled communication. A PubSub patterned communication between a publisher (sender) and subscriber (receiver) involves transmitted messages characterized as classes, instead of being passed as entire messages. Most PubSub implementations on the Web are not aware of the context. Typically, you would wish a PubSub message to be only legible to the children of a selected node or solely readable by the ancestors of a selected child. In other words, typically, you do not need unrelated MVC parts to read your messages. The PubSub system in AngularJS is exactly that. The broadcast() perform can send a message to all or any child controllers, whereas the emit() perform can send a message to all or any ancestors. However, PubSub is not the only way to communicate with controllers. In fact, if all you are doing is telling different controllers to update their views once a property changes, you must want data binding. However, what I did not tell you is that scopes inherit the properties of their parent scopes. This means that if a property exists on the parent scope and a child scope modifi es it, then all different scopes that inherit from the constant parent will see constant modifi cation; their views will be updated mechanically by the current version of AngularJS.

• The whole of AngularJS is coupled along by Dependency Injection (DI). This is what it uses to manage your controllers and scopes. As a result, all of your controllers depend on DI to pass information in order to perform unit testing by injecting mock information into your controller and measuring the output and behavior. In fact, AngularJS already incorporates a mock communication protocol supplier to inject faux server responses into the controllers. This beats the additional ancient approach of taking a look at the acting Internet applications by making individual test pages that invoke one part, then interacting with it to envision whether or not it works.

The preceding points should provide ample explanation as to why AngularJS is so useful and powerful. Not all web apps use AngularJS. For instance, if you're writing a game or a computationally intensive mathematics program, there's no reason why AngularJS would suit your explicit downside domain. Except for generic Internet apps, it ought to function as a viable framework.

Introduction

[ 10 ]

Getting acquainted with the anatomy of AngularJSIn AngularJS applications, view is the Document Object Model (DOM), controllers are the JavaScript functions, and the model data keeps object properties. We need to understand that MVC is needed for many reasons. First, it offers you a mental model for where to place what; therefore, you do not need to invent it each time. Other people collaborating on your project will take a moment to understand what you've written, as they may perceive that you have victimized the MVC structure because you have added your code. Maybe most signifi cantly, we'll claim that it delivers nice edges in creating your app easier to grow, maintain, and test.

AngularJS is constructed around the belief that declarative programming ought to be used to build user interfaces and wire software package components, whereas imperative programming is great for expressing business logic. The framework adapts and extends ancient HTML to raise and serve dynamic content through two-way data binding that permits the automated synchronization of models and views. As a result, AngularJS de-emphasizes DOM's manipulation and improves its testability and performance.

Separation of the HTML DOM (view) from the application logic (controller) improves the testability of the code in the following way:

• Regard application testing to be of equal importance to application writing. Testing issue is dramatically laid low with the method with which the code is structured.

• 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.

• Provides structure for the journey of building associate degree application from planning the UI, through writing the business logic, to testing.

Chapter 1

[ 11 ]

A typical collaboration of the MVC elements is shown in the following fi gure:

The MVC pattern brings modularity to application developers and it enables:

• Reusable and extendable code• Separation of view logic from business logic• Allows simultaneous work between developers who are responsible for

different components (such as UI layer and core logic)• Code that is easier to maintain

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 specifi cally 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.

Introduction

[ 12 ]

ModelThe 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 modifi cation 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 modifi cation 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 quantifi ability 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 fi le, 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 specifi cally 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' : 'Orange Juice', 'Lunch' : 'Fruit Salad', 'Dinner' : 'Vegetable Rice' }

ViewA 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>

Chapter 1

[ 13 ]

ControllerThe 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 fl aunted 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>

A div tag holds a controller directive. Note that ctrlFood in ng-controller= "ctrlFood" is same as the function name.

The AngularJS design patternAngularJS looks like a traditional markup language with some new markup features that are known as templates. Once an AngularJS template starts the application, it parses and processes this new markup from the markup language (template). The markup is named as directives and we'll discuss this in detail in Chapter 2, Learning AngularJS Binding and Directives. Directives apply special behavior to markup language components. As an example, the ng-app attribute is coupled with a directive that mechanically initializes the application. AngularJS additionally defi nes a directive for the input components that add additional behavior to the element. As an example, the ng-model directive stores or updates the value of the input element.

Another reasonable markup utilized in HTML is the double curly braces fi lter. Once the page is loaded and it is encountered with this markup, it'll be replaced with the evaluated value of the markup. An expression in HTML may be a JavaScript-like code snippet that permits reading and writing of the variables. These variables don't seem to be global variables. AngularJS provides a scope, which is an object that refers to the application model. It's an execution context for expressions. Scopes are organized in gradable structures that mimic the DOM structure of the application. The markup additionally contains a fi lter; a fi lter formats the value of an expression in order to display it for the user. They will be utilized in view templates, controllers, or services, and it's a straightforward task to defi ne your own fi lter. The vital issue is that AngularJS provides live bindings. Whenever the input values are modifi ed, the values of the expressions are automatically recalculated and the DOM is updated with their values. The construct behind this is often the two-way data binding that we are going to discuss intimately in Chapter 2, Learning AngularJS Binding and Directives.

Introduction

[ 14 ]

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>

Chapter 1

[ 15 ]

Our logic for AngularControllers.js is as follows:

var app = angular.module('myApp', []);app.controller("myController", function ($scope) { $scope.countCarSelectionChanged = 0;

$scope.onCarSelectionChanged = function () {$scope.countCarSelectionChanged++; };

});

Downloading the example codeYou can download the example code fi les from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the fi les e-mailed directly to you.

Loading index.html into a browser will then produce what you see in the following screenshot:

Introduction

[ 16 ]

There are a few interesting things to note here:

• There are no classes or IDs within the markup language to identify where to connect event listeners.

• The myController class could be a plain JavaScript class and it doesn't inherit from something that AngularJS provides. It must be registered with AngularJS.

• The myController class has got the $scope object that it needed without having to create it.

• We did not have to call the myController class's constructor ourselves or fi gure out when to call it.

• When CarSelectionChanged is called using the ng-change directive, it will set the count of your favorite car, which was selected. We didn't have to register any event listeners or write any callbacks.

In the preceding code example, to select your favorite car as input in line 1, AngularJS specifi es 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- prefi xed elements, attributes, or CSS classes. It will match some regular HTML tags, such as input, and select them if they contain the ng- prefi xed 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 defi nition 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.

Chapter 1

[ 17 ]

In the preceding example, ng-controller introduces a directive that maps an AngularJS object called controller to the HTML section delimited by the current element. The controller is defi ned in the AngularControllers.js script, which is a globally accessible function. We call this function the controller constructor function. Note that the $scope parameter represents the current scope instance. This parameter gets initialized automatically by AngularJS; so, when the controller constructor function is executed, the scope is available and ready to use. Declaring a parameter in a component defi nition and expecting AngularJS to automatically provide it is the signature of the dependency injection mechanism. The controller will be discussed in Chapter 2, Learning AngularJS Binding and Directives.

The scope passed to the controller is also attached to the view represented by the HTML element with the ng-controller attribute. The controller and view share data through the model represented by the scope instance. Any property defi ned on the controller scope will also be visible to the HTML view.

In the preceding example, the <input> HTML element used the ng-model="name" directive, which holds the value of the <input> element. Another directive, ng-show="name" is used in the <h4> HTML element, which will show the <h4> element as soon as the user starts typing in the <input> element. The <h4> element will show the value of the ng-model of the <input> HTML element using {{name}} in <h4>.

The controller name, myController is declared and the $scope parameter is injected in the controller, as shown in AngularControllers.js. We will explain line 1 of the code fi le later in this book. This example also illustrates the fi rst property, carChangedCount of the controller. The initially assigned value to carChangedCount is zero. The onCarSelectionChanged property is used to declare a function. This function will increment the fi rst property, carChangedCount by 1 when it is called.

The onCarSelectionChanged property will evaluate the expression value of the attribute every time the selection changes. We can see that it is called in the example in the <select> element of HTML. The <select> element also uses the ng-model="selectedCar" directive, which will hold the value of a user's selection from the drop-down list. Another directive, ng-show is also used. This directive will show the {{name}} text your favorite cars, <b>{{selectedCar}}</b>. Here, {{name}} and {{selectedCar}} are the values from the <input> element and the <select> elements of HTML.

Introduction

[ 18 ]

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 fi gure shows the data fl ow of the preceding code example:

The following is a description of how AngularJS interacts with browsers:

• The browser loads the HTML and parses it into a DOM• The browser loads the angular.js script• AngularJS waits for the DOMContentLoaded event• AngularJS looks for the ng-app directive, which designates the

application boundary• The module specifi ed in ng-app (if any) is used to confi gure $injector• The ng-init directive assigns a value to the name property on the scope• The {{name}} property interpolates the expression to the application

Chapter 1

[ 19 ]

Notable built-in directivesAngularJS directives enable developers to specify custom and reusable hypertext markup language tags that moderate the behavior of certain elements. Some of the directives are as follows:

Directives Descriptionng-app This is the root element of the application that allows

behaviors to be modified through custom HTML tags.ng-bind This changes the text of an element to the value of an

expression. The <span ng bind="name"></span> expression will display the value of name inside the span. Any changes to name are reflected instantly in the DOM anywhere that the variable is used.

ng-model This is similar to ng-bind, but allows two-way data binding between the view and scope.

ng-model-options This allows you to tune how model updates are done.ng-class This allows class attributes to load dynamically.ng-controller This specifies a JavaScript controller class that evaluates

HTML expressions.ng-repeat This instantiates an element once per item from a collection.ng-show and ng-hide

This conditionally shows or hides an element depending on the value of a Boolean expression. Show and hide is achieved by setting the CSS display style.

ng-switch This conditionally instantiates one template from a set of choices depending on the value of a selection expression.

ng-view This is the base directive responsible for handling routes that resolve JSON before rendering templates driven by specified controllers.

ng-if This is the basic if statement directive. When the condition is false, the element is removed from the DOM. When true, a clone of the compiled element is reinserted.

Introduction

[ 20 ]

AngularJS – the conceptual overviewThe following section introduces the important parts of AngularJS:

• AngularJS is like other libraries in which you can invoke the functions as you want.

• Everything is designed to be used as a collaborative suite.• The applications designed using AngularJS need two things to start:

You need to load the angular.js library. 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).

The following code shows how to load AngularJS using CDN:

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

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 specifi c 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>

Chapter 1

[ 21 ]

If the application is developed where some other technology supposes to manage the application along with AngularJS, then add the ng-app directive to where the application HTML (DOM) will be managed by AngularJS:

<html><head><script src="~/scripts/angular.min.js"></script></head><body><divng-app>…</div></body></html>

TemplatesTemplates in AngularJS are HTML fi les 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).

DirectivesIn 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>"}});

Introduction

[ 22 ]

In the preceding code snippet, we created a directive, copyright. Directives have different types. Templates specify the HTML content that should be displayed when it's executed. By default, directives are restricted to attributes. However, to trigger them according to attributes, class, or name, we can use the restrict directive as follows:

• restrict: 'E': This means we should use an HTML tag to reference it, that is <copyright>

• restrict: 'A': This is for attribute that is <div copyright>• restrict: 'C': This is for class that is <div class="copyright">

The following code uses the HTML tag to reference the directive:

<body ng-app="app" >

<copyright></copyright>

</body>

FiltersAn AngularJS fi lter is accustomed to remodel data. A fi lter is added to expressions and directives that employ a pipe character. You would also use fi lters in controllers, services, and directives. You can also create your own fi lters, 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 fi lter used in the expression here, {{value | number:2}}, will only display a value of up to two decimal places. To implement a fi lter, the pipe symbol | is used after the variable, value.

Chapter 1

[ 23 ]

ServicesServices 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;});

It will be rendered in HTML, as follows:

<body ng-app="app"><div ng-controller="FirstController><input type="text" ng-model="payload.message"/></div>

<div ng-controller="SecondController"><input type="text" ng-model="payload.message"/></div></body>

Introduction

[ 24 ]

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 fi gure depicts the user services:

The following are some examples of a few services of AngularJS Framework:

Service Description$http This allows access to HTTP requests$resource This provides a higher-level abstraction to access REST-style services$document This is a jQuery wrapped reference to window.document$window This is a jQuery wrapped reference to window$timeout This is a wrapped version of window.setTimeout$parse This parses AngularJS expressions (for example, for binding with

ng-model or similar expressions) and provides accessor functions$cacheFactory This is usually used by other services whenever they need a scoped

cache of elements$filter This provides programmatic access to a filter function

Chapter 1

[ 25 ]

Dependency InjectionDependency 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 defi ne 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 compilerAfter AngularJS fi nds 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-specifi c 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 refl ected 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.

Introduction

[ 26 ]

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 fi nds, 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.

The overview of a single-page applicationA single-page application (SPA) represents that the application can solely have one page; hence the term single-page application. Let me explain how this can be possible. In an SPA, there's a main page, which is known as the shell page, and different pages that are dynamically created at runtime on the same page. In an SPA, when you go from one page to another, it's not really going to another page, but just loading totally different data on to the same page.

An SPA generally has initial resources and a content-generated server aspect on the initial application request. For all subsequent requests, it'll use the client-side code to load any required resources and to show content. An SPA can also have one or more static pages that serve as physical entry points of the application.

So in traditional applications, you must be aware that the pages usually blink and everything loads once more. This is not very effi cient with the use of bandwidth, particularly within the mobile world. SPAs are distinguished by their ability to redraw any part of the UI while not requiring a server round-trip to retrieve HTML. This can be achieved by separating information from the presentation of data by using a model layer that handles data and a view layer that reads from the models. In an SPA, we will load the initial content upfront, and so the various views (loaded as and when required) or the little reasonably mini websites may be loaded on the fl y and embedded into the shell.

Chapter 1

[ 27 ]

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 data-binding 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 fi nished 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.

Benefi ts of SPAsThe benefi ts 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

SummaryThis 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.

Introduction

[ 28 ]

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 fi rst 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.