Ads

Tuesday, 18 November 2014

Learn Angular JS

AngularJS is quite new. Version 1.0 was released in 2012.
Miško Hevery, a Google employee, started to work on AngularJS in 2009.
It is a JavaScript framework. It is a library written in JavaScript.
We can be added to a web page with a script tag
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Directives

AngularJS extends HTML with ng-directives.
  1. The ng-app directive defines an AngularJS application.
  2. ng-app directive defines the root element of an AngularJS application
  3. ng-app directive will auto-bootstrap (automatically initialize) when a web page is loaded
  4. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
  5. ng-app can have a value (like ng-app="myModule"), to connect code modules.
  6. The ng-bind directive binds application data to the HTML view. 
ng-init directive defines initial values for an AngularJS application
ng-model directive binds the 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.
 Example:
 <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>
   <div ng-app="">
   <p>Name: <input type="text" ng-model="name"></p>
   <p ng-bind="name"></p>
</div>
Output:                            Click Here to Try urself-1

 AngularJS directives are HTML attributes with an ng prefix.
The ng-init directive initialize AngularJS application variables

<div ng-app="" ng-init="firstName='John'">
     <p>The name is <span ng-bind="firstName"></span></p>
     <p>The name is {{ firstName }}</p>
</div>
Output: The name is John       Click Here to Try urself-2

In above you can use data-ng-, instead of ng-, if you want to make your page HTML5 valid

<div data-ng-app="" data-ng-init="firstName='John'">
    <p>The name is <span data-ng-bind="firstName"></span></p>
</div>

AngularJS directives used in this tutorial:
Directive Description Explained
ng-app Defines the root element of an application. Directives
ng-bind Binds the innerHTML of HTML elements to application data. Introduction
ng-click Defines the behavior when an element is clicked. HTML Events
ng-controller Defines the controller object for an application. Controllers
ng-disabled Binds application data to the HTML disabled attribute. HTML DOM
ng-hide Hides or shows HTML elements. HTML DOM
ng-include Includes HTML in an application. Includes
ng-init Defines initial values for an application. Directives
ng-model Binds the value of HTML controls to application data. Directives
ng-repeat Defines a template for each data in a collection. Directives
ng-show Shows or hides HTML elements. HTML DOM


Data Binding

The {{ firstName }} expression, is an AngularJS data binding expression.
Data binding in AngularJS, synchronizes AngularJS expressions with AngularJS data.
{{ firstName }} is synchronized with ng-model="firstName".

<div ng-app="" ng-init="quantity=1;price=5">
    Quantity: <input type="number"    ng-model="quantity">
    Costs:    <input type="number" ng-model="price">
    Total in dollar: {{ quantity * price }}
</div>
Output:              Try urself

Repeating HTML Elements

The ng-repeat directive repeats an HTML element:
ng-repeat directive clones HTML elements once for each item in a collection (in an array).

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

As Array element
<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>
Output:                   Try yourself

Expressions:

AngularJS expressions are written inside double braces: {{ expression }}.
If you remove the ng-app directive, HTML will display the expression as it is.

<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>
Output: My first expression: 10         Try urself-3
Number
<div ng-app="" ng-init="quantity=1;cost=5">
    <p>Total in dollar: {{ quantity * cost }}</p>
    <p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
Output: Total in dollar: 5        Try Urself-3
String
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
    <p>The name is {{ firstName + " " + lastName }}</p>
    <p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
Output: The full name is: John Doe    Try urself-3
Object
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
    <p>The name is {{ person.lastName }}</p>
    <p>The name is <span ng-bind="person.lastName"></span></p>
</div>
Output: The name is Doe    Try urself-3
Array
<div ng-app="" ng-init="points=[1,15,19,2,40]">
    <p>The third result is {{ points[2] }}</p>
    <p>The third result is <span ng-bind="points[2]"></span></p>
</div>
Output: The third result is 19      Try urself-3

Controllers

The ng-controller directive defines the controller.
The controller code will execute when the page loads.

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

    Full Name: {{fullName()}}
</div>

<script>
    function personController($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
            $scope.fullName = function() {
                   return $scope.firstName + " " + $scope.lastName;
            }
    }
</script>
||or||
<script src="personController.js"></script>
Try yourself-4

Filters

currency Format a number to a currency format.
filter Select a subset of items from an array.
lowercase Format a string to lower case.
orderBy Orders an array by an expression.
uppercase Format a string to upper case.

uppercase / lowercase filter format strings to upper case:
       <p>The name is {{ lastName | uppercase }}</p>
       <p>The name is {{ lastName | lowercase }}</p>
 currency filter formats a number as currency:
       <p>Total = {{ (quantity * price) | currency }}</p>
orderBy filter orders an array by an expression:
----------------------------Common Used for bellow codes -----------------
function namesController($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Hege',country:'Sweden'},
        {name:'Kai',country:'Denmark'}
    ];

---------Above can refer as <script src="namesController.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>    Try Here
 

 filter filter selects a subset of an array:   Try Here
    <ul>
          <li ng-repeat="x in names | filter:test | orderBy:'country'">
          {{ (x.name | uppercase) + ', ' + x.country }}
         </li>
   </ul>

AngularJS filters used in this tutorial:
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.
orderBy Orders an array by an expression.
uppercaseFormat a string to upper case.

Reading a JSON File

 http://www.w3schools.com/website/Customers_JSON.php
 [
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
}
]


AngularJS $http is a core service for reading data from web servers.
$http.get(url) is the function to use for reading server data.

<div ng-app="" ng-controller="customersController">
<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

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

</div>

<script>
function customersController($scope,$http) {
    $http.get("http://www.w3schools.com/website/Customers_JSON.php")
    .success(function(response) {$scope.names = response;});
}
</script>   

Try Here
  • AngularJS application is defined by ng-app. The application runs inside a <div>.
  • ng-controller directive names the controller object.
  • customersController function is a standard JavaScript object constructor.
  • AngularJS will invoke customersController with a $scope and $http object.
  • $scope is the application object (the owner of application variables and functions).
  • $http is an XMLHttpRequest object for requesting external data.
  • $http.get() reads static JSON data from http://www.w3schools.com/website/Customers_JSON.php.
  • If success, the controller creates a property (names) in the scope, with JSON data from the server.  
  • code above can also be used to fetch data from a database

Fetching Data From a PHP Server Running MySQL

 <div ng-app="" ng-controller="customersController">
<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
function customersController($scope,$http) {
    var site = "http://www.w3schools.com";
    var page = "/website/Customers_MySQL.php";
    $http.get(site + page)
    .success(function(response) {$scope.names = response;});
}
</script>  Try Here


Fetching Data From an ASP.NET Server Running SQL

<script>
function customersController($scope,$http) {
    var site = "http://www.w3schools.com";
    var page = "/website/Customers_SQL.aspx";
    $http.get(site + page)
    .success(function(response) {$scope.names = response;});
}
</script>

ng-disabled / ng-show / ng-hide Directive

ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
<div ng-app="">
     <p> <button ng-disabled="mySwitch">Click Me!</button> </p>
    <p> <input type="checkbox" ng-model="mySwitch">Button </p>
</div>
Try Here

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

</div>
Try Here

ng-click Directive

<div ng-app="" ng-controller="myController">
     <button ng-click="count = count + 1">Click me!</button>
     <p>{{ count }}</p>
</div>
<script>
function myController($scope) {
    $scope.count = 0;
}
</script>    Try Here

Module Example 


In this example,
"myApp.js" contains an application module definition.
"myCtrl.js" contains a controller.




<body>
<div ng-app="" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
function myCtrl($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
}
</script>
</body>
Try Here

<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>
</body>

Try Here


When to Load the Library

the AngularJS library is loaded in the <head> section.
load the AngularJS library in the <body> element, but before your own AngularJS scripts i.e either head section or before you define your code.

HTML Controls

  • input elements
  • select elements
  • button elements
  • textarea elements

Input Validation

Try Here; Some Examples Here from W3School

I recommend you to visit my below posts.....
 List search using Angular JS
 AngularJS in a SharePoint 2013 page to add list item using CSOM
 Use REST API & Angular JS Implement custom search for lookup & person/group   
 Questions on Angular JS

No comments:

Post a Comment

Ads