Labels

Wednesday, September 3, 2014

AngularJS - Quick Reference At One Go

This is a brief write-up on the Angular JS introduction. Here we'll see details on below:

 

1.     AngularJS Expressions

2.     AngularJS Controllers

3.     AngularJS Objects

4.     AngularJS Arrays

5.     AngularJS Filters

6.     AngularJS XMLHttpRequest - $http

7.     AngularJS Tables

8.     AngularJS SQL

9.     AngularJS HTML DOM

10.  AngularJS Events

11.  AngularJS Modules

12.  AngularJS Forms

13.  AngularJS Input Validation

14.  AngularJS BootStrap

 

 

AngularJS Directives

 

AngularJS extends HTML with ng-directives.

 

Ø  The ng-app directive defines an AngularJS application.

Ø  The ng-model directive binds the HTML (value of HTML controls (input, select, textarea)) to application data.

The ng-model directive can also:

Ø  Provide type validation for application data (number, email, required).

Ø  Provide status for application data (invalid, dirty, touched, error).

Ø  Provide CSS classes for HTML elements.

Ø  Bind HTML elements to HTML forms.

 

Ø  The ng-bind directive binds application data to the HTML view.

Ø  The ng-init directive initialize AngularJS application variables.

Ø  The ng-repeat directive repeats an HTML element.

Ø  The ng-disabled directive binds application data directly to the HTML disabled attribute.

Ø  The ng-show directive hides or shows an HTML element.

Ø  The ng-click directive defines an AngularJS click event.

Ø  The ng-show directive defines the visibility of an application.

 

 

In Other Words:

AngularJS starts automatically when the web page has loaded.

 

The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.

The ng-model directive binds the value of the input field to the application variable name.

The ng-bind directive binds the innerHTML of the <p> element to the application variable name.

 

 

<!DOCTYPE html>

<html>

<body>

<div ng-app=""  ng-init="name ='John'" >

<p>Input something in the input box:</p>

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

<p ng-bind="name"></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>

</html>

 

 

AngularJS Expressions

 

AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS expressions binds data to HTML the same way as the ng-bind directive.

AngularJS will "output" data exactly where the expression is written.

 

AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.

 

<!DOCTYPE html>
<html>
<body>
<div ng-app="">
  <p>My first expression: {{ 5 + 5 }} </p>
</div>

 

<div ng-app="" ng-init="quantity=1; cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>

 

<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is {{ firstName + " " + lastName }}</p>
</div>


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

 

AngularJS Controllers

 

AngularJS applications are controlled by controllers.

The ng-controller directive defines the controller.

The controller code will execute when the page loads.

 

A controller is a JavaScript Object, created by a standard JavaScript object constructor.

The $scope of the controller is the application (the HTML element) it is referred from.

 

 

<div ng-app="" ng-controller="personController">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
function
personController($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
}
</script>

------------------------------------------------------------

Controller Properties

 

<div ng-app="" ng-controller="personController">

First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{person.firstName + " " + person.lastName}}

</div>

<script>
function personController($scope) {
    $scope.person = {
        firstName: "John",
        lastName: "Doe"
    };
}
</script>

 

Application explained:

Ø  The ng-controller directive names the controller object - personcontroller

Ø  The function personController is a standard JavaScript object constructor.

Ø  The personcontroller object has one property: $scope.person.

Ø  The person object has two properties: firstName and lastName.

Ø  The ng-model directives binds the input fields to the controller properties (firstName and lastName).

 

------------------------------------------------------------

Controller Methods:

 

<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{person.fullName()}}

</div>

<script>
function personController($scope) {
    $scope.person = {
        firstName: "John",
        lastName: "Doe",
        fullName: function() {
            var x;
            x = $scope.person;
            return x.firstName + " " + x.lastName;
        }
    };
}
</script>

------------------------------------------------------------

Controller In External Files:

 

<div ng-app="" ng-controller="personController">


First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{person.firstName + " " + person.lastName}}
</div>


<script src="personController.js"></script>

------------------------------------------------------------

<div ng-app="" ng-controller="namesController">

<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>

<script src="namesController.js"></script>

 

namesController.js

function namesController($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Hege',country:'Sweden'},
        {name:'Kai',country:'Denmark'}
    ];
}

------------------------------------------------------------

 

AngularJS Objects

 

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>Last name is {{ person.lastName }}</p>

<p>First name is <span ng-bind="person. firstName "></span></p>
</div>

 

AngularJS Arrays

 

<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The points are {{ points[2]}}</p>
</div>

------------------------------------------------------------

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
<div>

------------------------------------------------------------

// Array of Objects

<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">

<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>
</div>

------------------------------------------------------------

AngularJS Filters

 

AngularJS filters can be used to transform data:

A filter can be added to an expression with a pipe character (|) and a filter.

 

Filter

Description

currency

Format a number to a currency format.

filter

Select a subset of items from an array.

lowercase

Format a string to lower case.

uppercase

Format a string to upper case.

orderBy

Orders an array by an expression.

 

 

<div ng-app="" ng-controller="personController">
<p>The name is {{ person.lastName | uppercase }}</p>
</div>

------------------------------------------------------------

<div ng-app="" ng-controller="costController">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>Total = {{ (quantity * price) | currency }}</p>
</div>

------------------------------------------------------------

<div ng-app="" ng-controller="namesController">
<ul>
  <li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>
<div>

------------------------------------------------------------

<div ng-app="" ng-controller="namesController">

<p><input type="text" ng-model="name"></p>
<ul>
  <li ng-repeat="x in names | filter:name | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>
</div>

 

Output:

  KAI, Denmark

  JANI, Norway

  HEGE, Sweden

 

AngularJS XMLHttpRequest - $http

 

AngularJS $http is a service for reading data from web servers.

$http.get(url) is the function to use for reading server data.

 

<!DOCTYPE html>

<html>

<body>

 

<div ng-app="" ng-controller="customersController">

 

<ul>

  <li ng-repeat="x in customers">

    {{ x.Name + ', ' + x.Country }}

  </li>

</ul>

 

</div>

 

<script>

function customersController($scope,$http) {

  $http.get("http://www.w3schools.com//website/Customers_JSON.php")

  .success(function(response) {$scope.customers= response;});

}

</script>

 

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

 

</body>

</html>

 

AngularJS Tables

 

Just use below, inplace of <ul> in above example

 

<table>
  <tr ng-repeat="x in customers ">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

 

<table>
  <tr ng-repeat="x in customers | orderBy : 'Country'">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country | uppercase}}</td>
  </tr>
</table>

 

AngularJS SQL

 

The code from the previous details AngularJS XMLHttpRequest - $http,  can also be used to read from databases.

http://www.w3schools.com/angular/angular_sql.asp

 

AngularJS HTML DOM

 

The ng-disabled directive binds application data directly to the HTML disabled attribute.

 

<div ng-app="">
<p>
<input type="checkbox" ng-model="mySwitch">Button
<button ng-disabled="mySwitch">Click Me!</button>
</p>

 

<p>

Value Of Checkbox Is: {{ mySwitch }}

</p>

 

</div>
</div>

------------------------------------------------------------

The ng-show directive hides or shows an HTML element.

 

<div ng-app="">
<p ng-show="true">I am visible.</p>
<p ng-show="false">I am not visible.</p>
</div>

 

You can use an expression that evaluates to true or false (like ng-show="hour < 12"), to hide and show HTML elements

 

<div ng-app="">

<div ng-app="" ng-init="quantity=5">


<p ng-show=" quantity ==5 ">I am visible.</p>
<p ng-show=" quantity >5 ">I am not visible.</p>
</div>

 

AngularJS Events

 

The ng-click directive defines an AngularJS click event.

 

<div ng-app="" ng-controller="myController">


<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>

</div>

 

 

The ng-show directive defines the visibility of an application.

·         The value ng-show="true" (boolean value) makes the element visible.

·         The value ng-show="false" makes the element invisible.

 

 

<div ng-app="" ng-controller="eventController">
<button ng-click="toggle()">Toggle</button>

<p ng-show="myVar">
First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{person.firstName + " " + person.lastName}}
</p>

<script src=" CommonController.js"></script>


</div>

 

AngularJS Modules

 

http://www.w3schools.com/angular/angular_modules.asp

 

 

AngularJS Forms

 

An AngularJS form is a collection of input controls.

 

HTML Controls:

 

HTML input elements are called HTML controls:

·         input elements

·         select elements

·         button elements

·         textarea elements

 

HTML Forms:

 

HTML forms group HTML controls together.

 

<div ng-app="" ng-controller="formController">


  <form novalidate>
    First Name:<br>  <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>  <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = </p>
  <p>master = </p>

 

<script src=" CommonController.js"></script>


</div>

 

 

AngularJS Input Validation

 

AngularJS forms and controls can provide validation services, and notify users of invalid input.

 

<!DOCTYPE html>
<html>

<body>
<h2>Validation Example</h2>

<form  ng-app=""  ng-controller=" validateController " name="myForm" novalidate>

<p>Username:<br>
  <input type="text" name="user" ng-model="user" required>
  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm.user.$error.required">Username is required.</span>
  </span>
</p>

<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  <span ng-show="myForm.email.$error.required">Email is required.</span>
  <span ng-show="myForm.email.$error.email">Invalid email address.</span>
  </span>
</p>

<p>
  <input type="submit"
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

<script src=" CommonController.js"></script>

</body>
</html>

 

AngularJS BootStrap

 

Note:

·         Bootstrap is a free collection of tools for creating websites and web applications.

·         It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions.

 

Twitter Bootstrap is the preferred style sheet for AngularJS Bootstrap.

Below is a complete HTML example, with all AngularJS directives and Bootstrap classes explained.

 

To include Twitter Bootstrap in your AngularJS application, add the following line to your <head> element:

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

 

Note: Check Attached - AngularBootStrap.JPG (For Form Design)

 

<!DOCTYPE html>
<html ng-app="">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>

<body ng-controller="userController">
<div class="container">

<h2>Bootstrap Demo</h2>
-------------------------------------------------------------
<table class="table table-striped">
  <thead>
  <tr>
    <th>Edit</th>
    <th>First Name</th>
    <th>Last Name</th>
  </tr>
  </thead>
<tbody>
  <tr ng-repeat="user in users">
    <td>
      <button class="btn" ng-click="editUser(user.id)">
      <span class="glyphicon glyphicon-pencil"></span>&nbsp;&nbsp;
Edit
      </button>
    </td>
    <td>{{ user.fName }}</td>
    <td>{{ user.lName }}</td>
  </tr>
</tbody>
</table>
-------------------------------------------------------------
<hr>
<button class="btn btn-success" ng-click="editUser('new')">
<span class="glyphicon glyphicon-user"></span>&nbsp;&nbsp;Create New User
</button>
<hr>
-------------------------------------------------------------
<h3 ng-show="edit">Create New User:</h3>
<h3 ng-hide="edit">Edit User:</h3>

<form class="form-horizontal">
  <div class="form-group">
  <label class="col-sm-2 control-label">First Name:</label>
  <div class="col-sm-10">
    <input type="text" ng-model="fName" ng-disabled="!edit" placeholder="First Name">
  </div>
  </div>
  <div class="form-group">
  <label class="col-sm-2 control-label">Last Name:</label>
  <div class="col-sm-10">
    <input type="text" ng-model="lName" ng-disabled="!edit" placeholder="Last Name">
  </div>
  </div>
  <div class="form-group">
  <label class="col-sm-2 control-label">Password:</label>
  <div class="col-sm-10">
    <input type="password" ng-model="passw1" placeholder="Password">
  </div>
  </div>
  <div class="form-group">
  <label class="col-sm-2 control-label">Repeat:</label>
  <div class="col-sm-10">
    <input type="password" ng-model="passw2" placeholder="Repeat Password">
  </div>
  </div>
</form>
-------------------------------------------------------------
<hr>
<button class="btn btn-success" ng-disabled="error || incomplete">
<span class="glyphicon glyphicon-save"></span>&nbsp;&nbsp;Save Changes
</button>
</div>
-------------------------------------------------------------
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src = "myUsers.js"></script>

<script src=" CommonController.js"></script>


</body>
</html>>

 

Bootstrap Classes Explained:

 

Element

Bootstrap Class

Defines

<div>

container

A content container

<table>

table

A table

<table>

table-striped

A striped table

<button>

btn

A button

<button>

btn-success

A success button

<span>

glyphicon

A glyph icon

<span>

glyphicon-pencil

A pencil icon

<span>

glyphicon-user

A user icon

<span>

glyphicon-save

A save icon

<form>

form-horizontal

A horizontal form

<div>

form-group

A form group

<label>

control-label

A control label

<label>

col-sm-2

A 2 columns span

<div>

col-sm-10

A 10 columns span

 

 

Below is the CommonController.js file, used in all above examples:

 

CommonController.js:

 

<script>

function personController($scope) {

    $scope.person = {

        firstName: "John",

        lastName: "Doe",

        fullName: function() {

            var x;

            x = $scope.person;

            return x.firstName + " " + x.lastName;

        }

    };

}

 

function namesController($scope) {

    $scope.names = [

        {name:'Jani',country:'Norway'},

        {name:'Hege',country:'Sweden'},

        {name:'Kai',country:'Denmark'}

    ];

}

 

function costController($scope) {

    $scope.quantity = 1;

    $scope.cost = 5;

}

 

function customersController($scope,$http) {

  $http.get("http://www.w3schools.com//website/Customers_JSON.php")

  .success(function(response) {

                $scope.customers= response;

              });

}


function eventController($scope) {
    $scope.person = {
        firstName: "John",
        lastName: "Doe"
    };
    $scope.myVar = true;
    $scope.toggle = function() {
        $scope.myVar = !$scope.myVar;
    };
}

 

function formController ($scope) {
    $scope.master = {firstName: "John", lastName: "Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
};

 

function validateController($scope) {
    $scope.user = 'John Doe';
    $scope.email = 'john.doe@gmail.com';
}

 

function userController($scope) {


$scope.fName = '';
$scope.lName = '';
$scope.passw1 = '';
$scope.passw2 = '';


$scope.
users = [
{id:1, fName:'Hege',  lName:"Pege" },
{id:2, fName:'Kim',   lName:"Pim" },
{id:3, fName:'Sal',   lName:"Smith" },
{id:4, fName:'Jack',  lName:"Jones" },
{id:5, fName:'John',  lName:"Doe" },
{id:6, fName:'Peter', lName:"Pan" }
];


$scope.edit = true;
$scope.error = false;
$scope.incomplete = false;

$scope.
editUser = function(id) {
  if (id == 'new') {
    $scope.edit = true;
    $scope.incomplete = true;
    $scope.fName = '';
    $scope.lName = '';
    } else {
    $scope.edit = false;
    $scope.fName = $scope.users[id-1].fName;
    $scope.lName = $scope.users[id-1].lName;
  }
};

$scope.$watch('fName', function() {$scope.test();});
$scope.$watch('lName', function() {$scope.test();});

$scope.$watch('passw1',function() {$scope.test();});
$scope.$watch('passw2',function() {$scope.test();});

//Note: $scope.watch    - Watches model variables


$scope.
test = function() {
  if ($scope.passw1 !== $scope.passw2) {
    $scope.error = true;
    } else {
    $scope.error = false;
  }
  $scope.incomplete = false;


  if ($scope.edit && (!$scope.fName.length ||
  !$scope.lName.length ||
  !$scope.passw1.length || !$scope.passw2.length)) {
       $scope.incomplete = true;
  }
};
}

 

</script>

 

Hope this helps.

 

Regards,

Arun Manglick

1 comment:

  1. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog
    Angularjs Training In Hyderabad

    ReplyDelete