Tuesday, 26 July 2016

                          

                          AngularJS

___________________________________________________


https://hello-angularjs.appspot.com/angularjs-restful-apis-get-method-code-example
https://docs.angularjs.org/api/auto/service/$injector


Background

In a traditional Web app, every time the app calls the server, the server renders a new HTML page. This triggers a page refresh in the browser. If you’ve ever written a Web Forms application or PHP application, this page lifecycle should look familiar.


In an SPA(AngularJS, AJAX), after the first page loads, all interaction with the server happens through AJAX calls. These AJAX calls return data—not markup—usually in JSON format. The app uses the JSON data to update the page dynamically, without reloading the page. Figure 2 illustrates the difference between the two approaches.

AngularJS starts automatically when the web page has loaded.


AngularJs treats quotes  single quote(')= double quote(" ")
and it is case sensitive i.e a <> A





1.)The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
ex: <div ng-app="">   </div>

 if ng-app="" that is empty then only ng-model values can be useful
otherwise means ng-app="myApp" contains any value then we have to use controllers to get the value from Scope.


2.)ng-init used to intialize the variables at ng-app level
ex: <div ng-app="" ng-init="myCol='lightblue'">   </div>
ex:
<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>

2.)The ng-model directive binds the value of the input field Values Validation purpose to the application variable name like input type as text, textarea, select...etc.
 ex:

<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p ng-bind="name"></p>
</div>


3.)The ng-bind directive binds the innerHTML of the <p> element to the application variable name.
ex:
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
  <p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>





Js will know as it is Angular Js with ng-app and ng-init:
---------------------------------------------------------
<div ng-app="" ng-init="firstName='John'">
</div>



<input type="text" ng-model="firstName"></p>
{{ firstName }}

calculations: {{ 5 + 5 }}




Controller:
------------
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>


<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: {{firstName + " " + lastName}}
</div>




Angular Module: (angular.module):

ex1: Addming Controller Module
var app = angular.module("myApp", []);

 app.controller("myCtrl"function($scope) {
   $scope.firstName = "John";
   $scope.lastName = "Doe";
});  



AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ng-.
The ng-app directive initializes an AngularJS application.
The ng-init directive initializes application data.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

ex2: Adding directive Module


You can invoke a directive by using:

  • Element name =E
  • Attribute=A
  • Class=C
  • Comment=M
  • By Default EA=elemnt and Attribute values exist in directive
ex: Directive By Element=E
<w3-tests-directive></w3-tests-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestsDirective", function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>

ex: Directive By Attribute=A
    here observe template is used

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});

</script>
<div w3-test-directive></div>



ex: Directive By Class=C
  Here observe return, and template are used

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        restrict : "C",
        template : "<h1>Made by a directive!</h1>"
    };
 });

</script>
<div class="w3-test-directive"></div>


ex: Directive By comment=M
  Here observe comment, restrict, replace, template fields

<!-- directive: w3-test-directive -->
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        restrict : "M",
        replace : true,
        template : "<h1>Made by a directive!</h1>"
    };
});

</script>

Angular Js Email Validation:
  Here ng-model, ng-show are mandatory
<form ng-app="" name="myForm">
    Email:
    <input type="email" name="myAddress" ng-model="text">
    <span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>

</form>


ng-model have the follwoing validation attibutes:
  • ng-empty  ex: input.ng-empty{}
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid ex: input.ng-valide{backgorund-color:"green"}
  • ng-invalid ex:input.ng-invalid{background-color:"red"}
  • ng-dirty
  • ng-pending
  • ng-pristine



AngularJS Filters: (| pipe symbol in {{expression}} )


ex: {{ lastName | uppercase }}

ng-repeat with  | symbol:
ex:<ul>
  <li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>


where names came from Scrope
$scope.names=[{name:'Naveen', country:'India'},
       {name:'praveen', country:'Australia'},
       {name:'Bhaaru', country:'India'}]
]


AngularJS Filters are as follws:
orderby:<li ng-repeat="x in names | orderby: 'country'">
filter,  <li ng-repeat="x in names | filter : 'i'">


AngularJS provides filters to transform data:

  • currency Format a number to a currency format.
  • date Format a date to a specified format.
  • filter Select a subset of items from an array.
  • json Format an object to a JSON string.
  • limitTo Limits an array/string, into a specified number of elements/characters.
  • lowercase Format a string to lower case.
  • number Format a number to a string.
  • orderBy Orders an array by an expression.
  • uppercase Format a string to upper case.

AngularJS Services:

-In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application.
-30 built-in services. 

|- $location service has methods which return information about the location of the current web page:
var app = angular.module('myApp', []);
app.controller('customersCtrl'function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});



|- $http service is one of the most common used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response
var app = angular.module('myApp', []);
app.controller('myCtrl'function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});


The $timeout Service
var app = angular.module('myApp', []);
app.controller('myCtrl'function($scope, $timeout) {
    $scope.myHeader = "Hello World!";
    $timeout(function () {
        $scope.myHeader = "How are you today?";
    }, 2000);
});


Create Your Own Service

To create your own service, connect your service to the module:
syntax:Create a service named hexafy:

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});



AngularJS $http


The AngularJS $http service makes a request to the server, and returns a response.

<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>


<script>
var app = angular.module('myApp', []);
app.controller('myCtrl'function($scope, $http) {
    $http.get("welcome.htm")
    .then(function(response) {
        $scope.myWelcome = response.data;
    });
});
</script>

Methods of $http service:

  • .get()
  • .put()
  • .post()
  • .delete()
  • .head()
  • .jsonp()
  • .patch()



Properties:(Response of get method url)

$http.get("welcome.htm")
    .then(function(response) {
        $scope.myWelcome = response.data;
    });

|-The response from the server is an object with these properties:
  •  .config the object used to generate the request.
  • .data a string, or an object, carrying the response from the server.
  • .headers a function to use to get header information.
  • .status a number defining the HTTP status.
  • .statusText a string defining the HTTP status.


var app = angular.module('myApp', []);
app.controller('myCtrl'function($scope, $http) {
    $http.get("wrongfilename.htm")
    .then(function(response) {
        //First function handles success        $scope.content = response.data;
    }, function(response) {
        //Second function handles error        $scope.content = "Something went wrong";
    });
});

|-get method
  |-then method
       if true  success function
       else error message function



JSON Records from the response object:

|-$scope.myData = response.data.records;


 Select Box Using ng-options

DropDown:
<select ng-model="" ng-options="x for x in names">

</select>
(or)
<select>
<option ng-repeat="x in names">{{x}}</option>

</select>
Note: ng-repeat directive has its limitations, the selected value must be a string:
Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeathas to be a string.

<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>
Here, x is the key represents value as Y


Scopes:

Scope of particular attribute is available upto that tag-level only
Ex: <div  ng-app="myApp">          </div>
Here, the Scope of the myApp is exist within div tag only
|-Scopes are attached to the DOM as $scope data property, 


$rootScope

Every application has a single root scope. All other scopes are descendant scopes
$injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.



ROUTING MODULE:
-----------------------------
with no page reloading, you can use the ngRoute module.

What is Routing in AngularJS?


If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), 
with no page reloading, you can use the ngRoute module.

-ngRoute,
-$routeProvider
   -templateurl:
   -

ex:
To create app:
 var app = angular.module("myApp", ["ngRoute"]);

To configure other pages:
app.config(function($routeProvider) {
$routeProvider
    .when("/start.html", {
        templateUrl : "main.htm",
        controller: "I love starting the html",
   template : "<h1>Main</h1><p>Click on the links to change this                                                               content</p>
  })
          .otherwise({
        template : "<h1>None</h1><p>Nothing has been selected,</p>"
                 Contoller:  "otherwise option"
                templateUrl : "sample.html"    }); })

To display that routeProvider html pages:
 <div ng-review> or <ng-review/> or <div class="ng-review">

-------------
Ex:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/">Main</a></p>

<a href="#red">Red</a>
<a href="#green">Green</a>
<a href="#blue">Blue</a>

<div ng-view></div>


<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.htm"
    })
    .when("/red", {
        templateUrl : "red.htm"
    })
    .when("/green", {
        templateUrl : "green.htm"
    })
    .when("/blue", {
        templateUrl : "blue.htm"
    });
});
</script>

<p>Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back to "main.htm"</p>
</body>
</html>


2Ex:
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.htm",
    })
    .when("/london", {
        templateUrl : "london.htm",
        controller : "londonCtrl"
    })
    .when("/paris", {
        templateUrl : "paris.htm",
        controller : "parisCtrl"
    });
});
app.controller("londonCtrl", function ($scope) {
    $scope.msg = "I love Londonsssssssss";
});
app.controller("parisCtrl", function ($scope) {
    $scope.msg = "I love Paris";
});


AngularJS Includes:

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

<div ng-include="'myFile.htm'"></div>

Ex:

<div ng-app="myApp" ng-controller="customersCtrl">
  <div ng-include="'myTable.htm'"></div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("customers.php").then(function (response) {
        $scope.names = response.data.records;
    });
});
</script>

where myTable.htm:
  <table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>

 watermark-text:

Ex:
<input type="text" ng-model="username" watermark-text="Enter your user Name....." >
      restrict: 'A',
                require: 'ngModel',
                link: function (scope, element, attr) {
                    $timeout(function () {
                        var onFocus = function () {
























No comments:

Post a Comment