Angular JS Magazine

marți, 13 ianuarie 2015

Reading Data From a Servlet Via Angular JS $http.get

In this tip you can see how to read data from a Servlet using $http.get. First, a simple servlet that returns a JSON string and belongs to the application named, AngularGET:

@WebServlet(name = "AtpPlayers", urlPatterns = {"/AtpPlayers"})
public class AtpPlayers extends HttpServlet {
 ...
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

  response.setContentType("application/json;charset=UTF-8");
 try (PrintWriter out = response.getWriter()) {

        out.println("[{\"name\": \"Nadal, Rafael (ESP)\", \"email\": \"nadalrafael@gmail.com\", \"rank\": \"1\"},"
                        + "{\"name\": \"Djokovic, Novak (SRB)\", \"email\": \"djokovicnovak@gmail.com\", \"rank\": \"2\"},"
                        + "{\"name\": \"Federer, Roger (SUI)\", \"email\": \"federerroger@gmail.com\", \"rank\": \"3\"},"
                        + "{\"name\": \"Wawrinka, Stan (SUI)\", \"email\": \"wawrinkastan@gmail.com\", \"rank\": \"4\"},"
                        + "{\"name\": \"Ferrer, David (ESP)\", \"email\": \"ferrerdavid@gmail.com\", \"rank\": \"5\"}]");
        }
    }
 ...
}

Now, a simple Angular page that communicate with this servlet:

<!DOCTYPE html>
<html>
    <head>    
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>      
    </head>
    <body ng-app="ATP_PLAYERS">  
        <div ng-controller="atpController">
            <h5>Loading ATP players from a Servlet</h5>
            <table>
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Name</th>
                        <th>E-mail</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in atp">
                        <td>{{item.rank}}</td>            
                        <td>{{item.name}}</td>
                        <td>{{item.email}}</td>
                    </tr>
                </tbody>
            </table>
        </div>    
     
        <script language="javascript" type="text/javascript">
          angular.module('ATP_PLAYERS', [])
           .controller('atpController', function ($scope, $http) {
              $http.get('/AngularGET/AtpPlayers').success(function (data, status, headers, config) {
                $scope.atp = data;
             });
         });
        </script>
    </body>
</html>






luni, 12 ianuarie 2015

Angular JS - Read/Write/Delete/Reset form Web Storage (Local/Session Storages) Using ngStorage

In this tip you can see how to work with Web Storage (local and session) using the ngStorage module.

Usage:

     $scope.terms = {small: "0", big: "0", percent: "100"};
  • write default value in local/session storage
          $localStorage = $localStorage.$default({small: $scope.terms.small});          
          $localStorage = $localStorage.$default({big: $scope.terms.big});
          $localStorage = $localStorage.$default({percent: $scope.terms.percent});
          $sessionStorage = $sessionStorage.$default({result: 0});
  • overwrite an exiting value
         $localStorage.small = $scope.terms.small;
         $localStorage.big = $scope.terms.big;
         $sessionStorage.result = result;
  • delete all
        $localStorage.$reset()
        $sessionStorage.$reset();
  • delete an object
          delete $localStorage.small;
          delete $localStorage.big;
  • reset an object
          $localStorage.$reset({small: "0",big: "0", percent: "100"});

Example:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../angular/angular.min.js"></script>
    <script src="../angular/ngStorage-master/ngStorage.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
    <script>
        angular.module("myModule", ['ngStorage'])
                .controller("myCtrl", function ($scope, $localStorage, $sessionStorage) {

                    $scope.terms = {small: "0", big: "0", percent: "100"};

                    $scope.$l_storage = $localStorage;
                    $scope.$s_storage = $sessionStorage;
                            
                    $localStorage = $localStorage.$default({small: $scope.terms.small});             
                    $localStorage = $localStorage.$default({big: $scope.terms.big});  
                    $localStorage = $localStorage.$default({percent: $scope.terms.percent}); 
                    $sessionStorage = $sessionStorage.$default({result: 0});

                    $scope.addTermsInLocalStorage = function(){
                      $localStorage.small = $scope.terms.small;
                      $localStorage.big = $scope.terms.big;

                      if(angular.isUndefined($localStorage.percent)){                       
                        $localStorage = $localStorage.$default({percent: $scope.terms.percent}); 
                      }
                      
                      var result = ($localStorage.small * $localStorage.percent)/$localStorage.big;
                      $scope.addResultInSessionStorage(result);
                    }; 

                    $scope.addResultInSessionStorage = function(result) {                  
                      $sessionStorage.result = result;
                    };                   

                    $scope.deleteSmallAndBigTermsFromLocalStorage = function(){                        
                      delete $localStorage.small;
                      delete $localStorage.big;
                    }

                    $scope.resetSmallAndBigTermsFromLocalStorageTo0 = function(){                        
                      $scope.terms = {small: "0", big: "0", percent: "100"};
                    }

                    $scope.deleteAllTermsFromLocalAndSessionStorage = function(){                        
                      $localStorage.$reset(); //delete all
                      $sessionStorage.$reset();
                     //$localStorage.$reset({small: "0",big: "0", percent: "100"}); //reset a specific object
                    }                    

                    $scope.$watch('terms', 'addTermsInLocalStorage()', true);
                });
    </script>
</head>
<body>
<div ng-app="myModule">
    <div id="myPanel" class="panel" ng-controller="myCtrl">
    <h5> Using ngStorage (local and session web storage)</h5>
    <table>  
      <tr>
        <td>Small term:</td>
        <td><input class="form-control" ng-model="terms.small"></td>    
        <td rowspan="2" align="center">
           <p>Result of computation: <span class='label label-primary'>
                {{$l_storage.small}} represents {{$s_storage.result | number:3}}% 
                      from {{$l_storage.big}}</span>
           </p>
       </td>
      </tr>
      <tr>
        <td>Big term:</td>
        <td><input class="form-control" ng-model="terms.big"></td>        
      </tr>             
      <tr>
       <td>
        <button ng-click="deleteSmallAndBigTermsFromLocalStorage()">
         Delete Small And Big Terms from Local Storage</button>
       </td>    
       <td>
        <button ng-click="deleteAllTermsFromLocalAndSessionStorage()">
          Delete All Terms from Local/Session Storage</button>
       </td>
       <td>
        <button ng-click="resetSmallAndBigTermsFromLocalStorageTo0()">
          Reset Small And Big Terms from Local Storage To 0</button>
       </td>
      </tr>
     </table>     

    </div>
</div>
</body>
</html>


vineri, 9 ianuarie 2015

Angular JS - Use $watch For Watching Multiple Things

In this tip, you can see three use cases for $watch:
  •  use $watch for watching all properties of an object
  •  use $watch for watching only some properties of the same object
  •  use $watch for watching only some properties for different objects
Per example, when you calculate the PS Eden Space for memory pools (current utilization), you need the used MB, committed MB and max available MB. You can easily group these info under a object, like this sample:

$scope.mp = { usedmb: 72, committedmb: 139, maxmb: 140 };

Now, the current utilization is computed in a function, like this:

$scope.computePSEdenSpace = function () {
    $scope.pses = ($scope.mp.usedmb * 100.0)/($scope.mp.maxmb);
}

If you let the user to provide these three info via input texts then you may need to watch the entire $scope.mp for changes, like this:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../angular/angular.min.js"></script>
<link href="../bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
 <script>
   angular.module("myModule", [])
            .controller("myCtrl", function ($scope) {
                  
            $scope.pses = 0.0;
            $scope.mp = { usedmb: 72, committedmb: 139, maxmb: 140 };

            $scope.computePSEdenSpace = function () {
              $scope.pses = ($scope.mp.usedmb * 100.0)/($scope.mp.maxmb);
            }

            $scope.$watch('mp', 'computePSEdenSpace()', true);
  });
  </script>
 </head>
<body>
<div ng-app="myModule">

    <div id="myPanel" class="panel" ng-controller="myCtrl">
    <h4 class="panel-header">$watch - Watching multiple things</h4>
    <hr/>
    <table>
      <tr>
       <td>Used (MB):</td>
       <td><input class="form-control" ng-model="mp.usedmb"></td>
      </tr>
      <tr>
       <td>Comitted (MB):</td>
       <td><input class="form-control" ng-model="mp.committedmb"></td>
      </tr>
      <tr>
       <td>Max Available (MB):</td>
       <td><input class="form-control" ng-model="mp.maxmb"></td>
      </tr>
   </table>
   <br/>
   <span class='label label-primary'>PS Eden Space:</span> 
   <strong>{{pses | number:1}}</strong>%
 </div>
</div>
</body>
</html>

This worked ok, but if you take a closer look to the formula nested in the $scope.computePSEdenSpace() function you will notice that it depends on used MB and max available MB, and is independent of comitted MB. Since we are watching the entire $scope.mp, this function is called when the user modify the committed MB also, which is useless. We can fix this by replacing the:

  $scope.$watch('mp', 'computePSEdenSpace()', true);

with the below concatenation:

$scope.$watch('mp.usedmb + mp.maxmb', 'computePSEdenSpace()');

Now, we watch only these two properties of the  $scope.mp object, and the $scope.computePSEdenSpace() function is not called anymore when the user modify the committed MB.

Note: Based on this example, you can even watch properties from different objects, by simply concatenating the corresponding properites!!!