What is AngularJS?

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 application's components clearly and succinctly. Angular's data binding and dependency injection eliminate 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

  • A a powerful JavaScript based development framework to create RICH Internet Application(RIA).
  • It provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way.
  • Application written in AngularJS is cross-browser compliant. 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 licensed under the Apache License version 2.0.

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

Core Features

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

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

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

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

Core Feature (contd.)

Templates − These are the rendered view with information from the controller and model. These can be a single file (like 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 dividing an application into different parts (called Model, View and Controller), each with distinct responsibilities. 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 linking allows you to encode the state of application in the URL so that it can be bookmarked. The application 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 application easier to develop, understand, and test.

Set up AngularJS

https://angularjs.org

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

Simple AngularJS App

Save the code as index.html and open it in browser. You will see an output as  below.

Welcome AngularJS starter app!

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.

An AngularJS application consists of following three important parts −

ng-app − This directive defines and links an AngularJS application to HTML.

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

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

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

Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behaves in same way as ng-bind directives. AngularJS application expressions are pure javascript expressions and outputs the data where they are used.

Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>

Using strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>

Using object
<p>Roll No: {{student.rollno}}</p>

Using array
<p>Marks(Math): {{marks[3]}}</p>

Expressions

AngularJS Filters

Below are the examples of commonly used filters :

Uppercase Filter

Name in Upper Case: {{student.fullName() | uppercase}}

Lowercase Filter

Name in Lower Case: {{student.fullName() | lowercase}}

filter filter

Currency filter

Add currency filter to an expression returning number using pipe character. It prints fees using currency format.

Enter fees: <input type = "text" ng-model = "student.fees">
fees: {{student.fees | currency}}

To display only required subjects, we've used subjectName as filter.

Enter subject: <input type = "text" ng-model = "subjectName">
Subject:
<ul>
  <li ng-repeat = "subject in student.subjects | filter: subjectName">
     {{ subject.name + ', marks:' + subject.marks }}
  </li>
</ul>

Angular Directives

ng-disabled - disables a given control.

ng-show -  shows a given control.
ng-hide     - hides a given control.
  ng-click  -  represents a AngularJS click event.
<input type = "checkbox" ng-model = "enableDisableButton">Disable Button
<button ng-disabled = "enableDisableButton">Click Me!</button>

<input type = "checkbox" ng-model = "showHide1">Show Button
<button ng-show = "showHide1">Click Me!</button>

<input type = "checkbox" ng-model = "showHide2">Hide Button
<button ng-hide = "showHide2">Click Me!</button>

<p>Total click: {{ clickCounter }}</p>
<button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>


For more directives please refer to documentation.

 Angularjs also allows us to create custom directives.

AngularJS Modules

AngularJS supports modular approach. Modules are used to separate logics say services, controllers, application etc. and keep the code clean. We define modules in separate js files and name them as per the module.js file.

Let's see how we can work with modules. Create two modules:

Application Module - Used to initialize application with controller(s), service(s),directive(s), filter(s)

Controller Module - Used to define controller

//mycontroller.js
mainApp.controller("mycontroller", function($scope) {
 ....
});
//mainapp.js
var mainApp = angular.module("mainApp", []);
<html>
   <head>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      <script src = "mainapp.js"></script>
      <script src = "mycontroller.js"></script> 
   </head>
   <body>
      <div ng-app = "mainApp" ng-controller = "myController">
        ...
      </div>
   </body>
</html>

AngularJS Ajax

AngularJS provides $http control which works as a service to read data from the server. The server makes a REST API call to get the desired results. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner −

<html>
   <body>
      <div ng-app = "" ng-controller = "studentController">
         <table>
            <tr><th>Name</th><th>Roll No</th><th>Percentage</th></tr>
            <tr ng-repeat = "student in students">
               <td>{{ student.Name }}</td><td>{{ student.RollNo }}</td>
    <td>{{ student.Percentage }}</td>
            </tr>
         </table>
      </div>
      <script>
         function studentController($scope,$http) {
           var url = "<end point url>";
            $http.get(url).success( function(response) {
               $scope.students = response;
            });
         }
/*sameple data:
[{"Name" : "Mahesh Parashar","RollNo" : 101,"Percentage" : "80%"}
...
]*/
      </script>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

AngularJS Views

AngularJS supports Single Page Application via multiple views on a single page. To do this AngularJS has provided ng-view and ng-template directives and $routeProvider services.

ng-view
ng-view tag simply creates a place holder where a corresponding view (html or ng-template view) can be placed based on the configuration.

<div ng-app = "mainApp">
   ...
   <div ng-view></div>
</div>

ng-template
ng-template directive is used to create an html view using script tag. It contains "id" attribute which is used by $routeProvider to map a view with a controller.

<div ng-app = "mainApp">
   ...
   <script type = "text/ng-template" id = "addStudent.htm">
      <h2> Add Student </h2>
      {{message}}
   </script>
</div>

$routeProvider

$routeProvider is the key service which set the configuration of urls, map them with the corresponding html page or ng-template, and attach a controller with the same.

<div ng-app = "mainApp">
   ...
   <script type = "text/ng-template" id = "addStudent.htm">
      <h2> Add Student </h2>
      {{message}}
   </script>
</div> 
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
   $routeProvider.
   when('/addStudent', {
      templateUrl: 'addStudent.htm', controller: 'AddStudentController'
   }).
   when('/viewStudents', {
      templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController'
   }).
   otherwise({
      redirectTo: '/addStudent'
   });
}]);

Angular Services

Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable. Services are normally injected using dependency injection mechanism of AngularJS.

There are two ways to create a service: 1. Factory 2. Service

<body>
      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>Enter a number: <input type = "number" ng-model = "number" /></p>
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>Result: {{result}}</p>
      </div>
      <script>
         var mainApp = angular.module("mainApp", []);
         mainApp.factory('MathService', function() {
            var factory = {};
            factory.multiply = function(a, b) {
               return a * b
            }
            return factory;
         });
         mainApp.service('CalcService', function(MathService){
            this.square = function(a) {
               return MathService.multiply(a,a);
            }
         });
         mainApp.controller('CalcController', function($scope, CalcService) {
            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);
            }
         });
      </script>
</body>
...

Internationalization

AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script.

<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>

Thank you.

Questions?

Made with Slides.com