Tuesday, 1 May 2018

024 AngularJS $apply() $digest() $watch()


AngularJS $apply() $digest() $watch()

$apply() , $digest(), $watch() are the core element of AngularJS application . AngularJS support data binding ,than means change in
one html control property will effect the other part of binding.Basically model is updated when you change
html control property.$apply() , $digest() , $watch() are used to observed the changes when data bind any part changes.


  • $watch() : $watch function watch the changes of variable in the $scope object.$watch function is attached with all $scope variable .Changes made in this variable update binding .The $watch() function is also used for custom watch for any events.
  • $digest() : Any changes made in $watch() variable ,$digest()  function call corresponding event listener functions  and update those values in view with new values.$digest() iterates through all the watches and checks any value updated.
  • $apply():$apply() function is used to execute expressions in DOM area. $apply() function forcefully finishes execution and   it will call $digest() function to update all data bindings.

Live Demo

Example of WatchEnter Text:
Old Value :{{oldval}}
New Value :{{newval}}
Example of Digest Current Date Time :{{currentDateTime}}
Example of Apply Current Date Time :{{msg}}


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


<script type="text/javascript">

               var app = angular.module('myApp', []);

                     app.controller('myController', function ($scope) 
           {

                     $scope.newval = '';
                     $scope.oldval = '';
                     $scope.$watch('myModel', function (newval, oldval) {

                     $scope.newval = newval;
                     $scope.oldval = oldval;

                  });


                  var event = document.getElementById("btndigest");
                  event.addEventListener('click', function () {
                  $scope.currentDateTime = new Date();
                  $scope.$digest();

});


$scope.Apply = function () 
 {
            return $scope.msg = "Example of Manually Apply.";
            $scope.$apply();
};


});

</script>
</head>
<body>
                 <div ng-app="myApp" ng-controller="myController">
<div style="width: 300px;">
<fieldset>
                     <legend>Example of Watch</legend>Enter Text:<input type="text" ng-model="myModel" /><br />
            <span>Old Value :{{oldval}}</span><br />
            <span>New Value :{{newval}}</span><br />
</fieldset>
<fieldset>
            <legend>Example of Digest</legend>
             <input type="button" value="Click to digest." id="btndigest" />
             <span>Current Date Time :{{currentDateTime}}</span><br />
</fieldset>
<fieldset>
              <legend>Example of Apply</legend>
              <input type="button" value="Click to Apply Manually." id="Button1" ng-click="Apply()" />
<span>Current Date Time :{{msg}}</span>
</fieldset>
</div>
</div>
</body>
</html>
</div>


The above example show how $apply() , $digest(), $watch() works. The first example is of $watch(). We have discussed earlier , AngularJS monitor each change in $scope variable.$watch() here monitor each changes of scope , the example show how $watch() monitor , what was the old value and what is the new value.

$digest() example set the current date time in the scope variable when click ,if found any changes , corresponding event listener is call to update view.


$apply() example set the scope variable to a specific string.When
$apply() is called , it forced to call $digest().


   

Monday, 30 April 2018

023 AngularJS angular.forEach

AngularJS angular.forEach

AngularJS has inbuilt iterator to iterator through object collcetion .This functionality works both on object collection and array.'angular.forEach' directive is used for this purpose.

Below is the example of iterator on Array.

Example







<!DOCTYPE >
<head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

</head>

<script>
 
           var app = angular.module("myApp", []);
                    app.controller("myController", function ($scope) 
           {

                       $scope.arr = ['Student 1', 'Student 2', 'Student 3', 'Student 4'];
                       $scope.idx = [];

                        angular.forEach($scope.arr, function (value, index) 
             {
                           $scope.idx.push(value);
                       });

});

</script>
<div style="background-color: #F0F0F0; width: 400px;">
        <div ng-app="myApp">
            <div ng-controller="myController" >
               <span ng-repeat="obj in idx">{{obj}}<br/></span>
           </div>
         </div>
</div>

Output :

Student 1Student 2Student 3Student 4

Below is the example of iterator on object collection.


Example



<!DOCTYPE >
<head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

</head>

<script>
var app = angular.module("myApp", []);
       app.controller("myController", function ($scope)
      {

            var values = [{ name: 'Student 1', gender: 'male' }, { name: 'Student 2', gender: 'male' }, { name: 'Student 3', gender: 'male'}];

            $scope.idx = [];

angular.forEach(values, function (value, key)
{

$scope.idx.push(value.name);
});

});

</script>
<div style="background-color: #F0F0F0; width: 400px;">
<div ng-app="myApp">
<div ng-controller="myController" >
<span ng-repeat="obj in idx">{{obj}}<br/></span>
</div>
</div>
</div>


Output :

Student 1Student 2Student 3

022 AngularJS JSON Serializes and Deserializes

AngularJS JSON Serializes and Deserializes

AngularJS support JSON . You can Serializes and Deserializes object from AngularJS inbuilt fucntion.'angular.toJson()' Serializes object from JavaScript object to JSON string.'angular.fromJson()' Deserializes JSON string and returns an JavaScript object.

Example 1 ( JavaScript object to JSON)
 
<!DOCTYPE >
<head>
         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
 
<script>
       var app = angular.module("myApp", []);
       app.controller("myController", function ($scope)
       {
          $scope.model =
          {
                student:
                {
                           firstname: "Ayan",
                           lastname: "Banerjee"
                 },
                address: 
         {
                           city: "Kolkata",
                           state: "South ,24 Pgs(s)"
               }
         };

        $scope.jsonData = angular.toJson($scope.model);
});

</script>
<div style="background-color: #F0F0F0; width: 400px;">
<div ng-app="myApp">
        <div ng-controller="myController" >
        <span>{{jsonData}}</span>
</div>
</div>
</div>

Output :
{"person":{"firstname":"Ayan","lastname":"Banerjee"},"address":{"city":"Kolkata","state":"South ,24 Pgs(s)"}}

 
Example 2  ( JavaScript object to JSON)


<!DOCTYPE >
<head>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script>

var app = angular.module("myApp", []);
        app.controller("myController", function ($scope)
        {

               var Obj = {};
               Obj.weight = 75;
               Obj.height = 180;
               Obj.colors = {};
               Obj.colors.r = 150;
               Obj.colors.g = 278;
               Obj.colors.b = 300;

                $scope.obj = Obj;

              $scope.SerialisedObj = angular.toJson($scope.obj, true);
});

</script>
<div style="background-color: #F0F0F0; width: 400px;">
<div ng-app="myApp">
<div ng-controller="myController" >
<span>{{SerialisedObj}}</span>
</div>
</div>
</div>

Output :

{ "weight": 75, "height": 180, "colors": { "r": 150, "g": 278, "b": 300 } } 




 
Example 1 (JSON to JavaScript object)
<!DOCTYPE >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>

<script>
         var app = angular.module("myApp", []);
         app.controller("myController", function ($scope)
         {

               var json = '{"name":"Ayan","Hobby":{"Reading":["Story","Novel","Short Story"]}}';

                $scope.obj = angular.fromJson(json);

          });

</script>

<div style="background-color: #F0F0F0; width: 400px;">
<div ng-app="myApp">
          <div ng-controller="myController" >
          <span>Name : {{obj.name}}</span><br/>
           <span ng-repeat="obj in obj.Hobby.Reading">{{obj}}<br/></span>
</div>
</div>
</div>

Output :

Name : Ayan
StoryNovelShort Story


 





 

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...