English 中文(简体)
AngularJS - Quick Guide
  • 时间:2024-11-03

AngularJS - Quick Guide


Previous Page Next Page  

AngularJS - Overview

What is AngularJS?

AngularJS is an open source web apppcation framework. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.

Definition of AngularJS as put by its official documentation is as follows −

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML s syntax to express your apppcation s components clearly and succinctly. Angular s data binding and dependency injection epminate much of the code you currently have to write. And it all happens within the browser, making it an ideal partner with any server technology.

Features

    AngularJS is a powerful JavaScript based development framework to create RICH Internet Apppcation(RIA).

    AngularJS provides developers options to write cpent side apppcation (using JavaScript) in a clean MVC(Model View Controller) way.

    Apppcation written in AngularJS is cross-browser comppant. AngularJS automatically handles JavaScript code suitable for each browser.

    AngularJS is open source, completely free, and used by thousands of developers around the world. It is pcensed under the Apache License version 2.0.

Overall, AngularJS is a framework to build large scale and high performance web apppcation while keeping them as easy-to-maintain.

Core Features

Following are most important core features of AngularJS −

    Data-binding − It is the automatic synchronization of data between model and view components.

    Scope − These are objects that refer to the model. They act as a glue between controller and view.

    Controller − These are JavaScript functions that are bound to a particular scope.

    Services − AngularJS come with several built-in services for example $https: to make a XMLHttpRequests. These are singleton objects which are instantiated only once in app.

    Filters − These select a subset of items from an array and returns a new array.

    Directives − Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel...)

    Templates − These are the rendered view with information from the controller and model. These can be a single file (pke index.html) or multiple views in one page using "partials".

    Routing − It is concept of switching views.

    Model View Whatever − MVC is a design pattern for spaniding an apppcation into different parts (called Model, View and Controller), each with distinct responsibipties. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View Whatever.

    Deep Linking − Deep pnking allows you to encode the state of apppcation in the URL so that it can be bookmarked. The apppcation can then be restored from the URL to the same state.

    Dependency Injection − AngularJS has a built-in dependency injection subsystem that helps the developer by making the apppcation easier to develop, understand, and test.

Concepts

Following diagram depicts some important parts of AngularJS which we will discuss in detail in the subsequent chapters.

AngularJS Concepts

Advantages of AngularJS

    AngularJS provides capabipty to create Single Page Apppcation in a very clean and maintainable way.

    AngularJS provides data binding capabipty to HTML thus giving user a rich and responsive experience

    AngularJS code is unit testable.

    AngularJS uses dependency injection and make use of separation of concerns.

    AngularJS provides reusable components.

    With AngularJS, developer write less code and get more functionapty.

    In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.

On top of everything, AngularJS apppcations can run on all major browsers and smart phones including Android and iOS based phones/tablets.

Disadvantages of AngularJS

Though AngularJS comes with lots of plus points but same time we should consider the following points −

    Not Secure − Being JavaScript only framework, apppcation written in AngularJS are not safe. Server side authentication and authorization is must to keep an apppcation secure.

    Not degradable − If your apppcation user disables JavaScript then user will just see the basic page and nothing more.

The AngularJS Components

The AngularJS framework can be spanided into following three major parts −

    ng-app − This directive defines and pnks an AngularJS apppcation to HTML.

    ng-model − This directive binds the values of AngularJS apppcation data to HTML input controls.

    ng-bind − This directive binds the AngularJS Apppcation data to HTML tags.

AngularJS - Environment Setup

In this chapter we will discuss about how to set up AngularJS pbrary to be used in web apppcation development. We will also briefly study the directory structure and its contents.

When you open the pnk https://angularjs.org/, you will see there are two options to download AngularJS pbrary −

AngularJS Download

    View on GitHub − Cpck on this button to go to GitHub and get all of the latest scripts.

    Download AngularJS 1 − Or cpck on this button, a screen as below would be seen −

AngularJS Download

    This screen gives various options of using Angular JS as follows −

      Downloading and hosting files locally

        There are two different options legacy and latest. The names itself are self descriptive. legacy has version less than 1.2.x and latest has 1.5.x version.

        We can also go with the minified, uncompressed or zipped version.

      CDN access − You also have access to a CDN. The CDN will give you access around the world to regional data centers that in this case, Google host. This means using CDN moves the responsibipty of hosting files from your own servers to a series of external ones. This also offers an advantage that if the visitor to your webpage has already downloaded a copy of AngularJS from the same CDN, it won t have to be re-downloaded.

    Try the new angularJS 2 − Cpck on this button to download Angular JS beta 2 version.This version is very fast, mobile supported and flexible compare to legacy and latest of AngularJS 1

We are using the CDN versions of the pbrary throughout this tutorial.

Example

Now let us write a simple example using AngularJS pbrary. Let us create an HTML file myfirstexample.html as below −

<!doctype html>
<html>
   
   <head>
      <script src = "https://ajax.googleapis.com/ajax/pbs/angularjs/1.5.2/angular.min.js"></script>
   </head>
   
   <body ng-app = "myapp">
      
      <span ng-controller = "HelloController" >
         <h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
      </span>
      
      <script>
         angular.module("myapp", [])
         
         .controller("HelloController", function($scope) {
            $scope.helloTo = {};
            $scope.helloTo.title = "AngularJS";
         });
      </script>
      
   </body>
</html>

Following sections describe the above code in detail −

Include AngularJS

We have included the AngularJS JavaScript file in the HTML page so we can use AngularJS −

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

If you want to update into latest version of Angular JS, use the following script source or else Check the latest version of AngularJS on their official website.

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

Point to AngularJS app

Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below −

<body ng-app = "myapp">
</body>

View

The view is this part −

<span ng-controller = "HelloController" >
   <h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</span>

ng-controller tells AngularJS what controller to use with this view. helloTo.title tells AngularJS to write the "model" value named helloTo.title to the HTML at this location.

Controller

The controller part is −

<script>
   angular.module("myapp", [])
   
   .controller("HelloController", function($scope) {
      $scope.helloTo = {};
      $scope.helloTo.title = "AngularJS";
   });
</script>

This code registers a controller function named HelloController in the angular module named myapp. We will study more about modules and controllers in their respective chapters. The controller function is registered in angular via the angular.module(...).controller(...) function call.

The $scope parameter passed to the controller function is the model. The controller function adds a helloTo JavaScript object, and in that object it adds a title field.

Execution

Save the above code as myfirstexample.html and open it in any browser. You will see an output as below −

Welcome AngularJS to the world of Tutorialspoint!

When the page is loaded in the browser, following things happen −

    HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded, the angular global object is created. Next, JavaScript which registers controller functions is executed.

    Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function.

    Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page is now ready.

AngularJS - MVC Architecture

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web apppcations. A Model View Controller pattern is made up of the following three parts −

    Model − It is the lowest level of the pattern responsible for maintaining data.

    View − It is responsible for displaying all or a portion of the data to the user.

    Controller − It is a software Code that controls the interactions between the Model and View.

MVC is popular because it isolates the apppcation logic from the user interface layer and supports separation of concerns. The controller receives all requests for the apppcation and then works with the model to prepare any data needed by the view. The view then uses the data prepared by the controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows.

AngularJS MVC

The Model

The model is responsible for managing apppcation data. It responds to the request from view and to the instructions from controller to update itself.

The View

A presentation of data in a particular format, triggered by the controller s decision to present the data. They are script-based template systems such as JSP, ASP, PHP and very easy to integrate with AJAX technology.

The Controller

The controller responds to user input and performs interactions on the data model objects. The controller receives input, vapdates it, and then performs business operations that modify the state of the data model.

AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS uses MVC methodology.

AngularJS - First Apppcation

Before we start with creating actual HelloWorld apppcation using AngularJS, let us see what are the actual parts of a AngularJS apppcation. An AngularJS apppcation consists of following three important parts −

    ng-app − This directive defines and pnks an AngularJS apppcation to HTML.

    ng-model − This directive binds the values of AngularJS apppcation data to HTML input controls.

    ng-bind − This directive binds the AngularJS Apppcation data to HTML tags.

Steps to create AngularJS Apppcation

Step 1: Load framework

Being a pure JavaScript framework, It can be added using <Script> tag.

<script src = "https://ajax.googleapis.com/ajax/pbs/angularjs/1.3.14/angular.min.js">
</script>

Step 2: Define AngularJS Apppcation using ng-app directive

<span ng-app = "">
   ...
</span>

Step 3: Define a model name using ng-model directive

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

Step 4: Bind the value of above model defined using ng-bind directive.

<p>Hello <span ng-bind = "name"></span>!</p>

Steps to run AngularJS Apppcation

Use above mentioned three steps in an HTML page.

testAngularJS.htm

<html>
   <head>
      <title>AngularJS First Apppcation</title>
   </head>
   
   <body>
      <h1>Sample Apppcation</h1>
      
      <span ng-app = "">
         <p>Enter your Name: <input type = "text" ng-model = "name"></p>
         <p>Hello <span ng-bind = "name"></span>!</p>
      </span>
      
      <script src = "https://ajax.googleapis.com/ajax/pbs/angularjs/1.3.14/angular.min.js">
      </script>
      
   </body>
</html>

Output

Open textAngularJS.htm in a web browser. Enter your name and see the result.