Angular JS Magazine

Se afișează postările cu eticheta Angular JS. Afișați toate postările
Se afișează postările cu eticheta Angular JS. Afișați toate postările

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

miercuri, 31 decembrie 2014

Angular JS - Use an Angular-Websocket Client with a Java Websocket Endpoint

In this tip you can see how to use the Angular Websocket module for connecting client applications to servers. For this case, we have a Java endpoint, as below:

package com.mycompany.angularws;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/atpendpoint")
public class ATPWSEndpoint {

    private static final Logger LOG = Logger.getLogger(ATPWSEndpoint.class.getName());
    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

    @OnMessage
    public String onMessage(String message) {
        if (message != null) {
            if (message.equals("HELLO SERVER")) {
                return "{\"hello\": \"Hello, if you need the ATP list just press the button ...\"}";
            } else if (message.equals("ATP SERVER")) {
                return "[{\"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\"}]";
            }
        }
        return "";
    }

    @OnOpen
    public void onOpen(Session peer) {
        LOG.info("Connection opened ...");
        peers.add(peer);
    }

    @OnClose
    public void onClose(Session peer) {
        LOG.info("Connection closed ...");
        peers.remove(peer);
    }
}


And, we access this endpoint like this:

  • the client sends a hello message (HELLO SERVER), and the server answers with a simple text (Hello, if you need the ATP list just press the button ...).
  • the client send another message, (ATP SERVER), and the server answers with a JSON object containing a list of tennis players
  • the client will display this list in a tabel

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" 
                 href="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-csp.css">
        <title>Angular JS Web-Socket</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        
    </head>
    <body ng-app="ATP_PLAYERS" class="ng-cloak">                
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
        <script src="resources/js/angular-websocket.js"></script>

        <div ng-controller="atpController">

            <div id="helloId"></div>

            <form ng-submit="submit()">                
                <button id="btnAtpId" type="submit" disabled>Send Message</button>
            </form>

            <table>
                <thead>
                    <tr>
                        <th>Rank</th>   
                        <th>Name</th>   
                        <th>E-mail</th>   
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in ATP.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', ['ngWebSocket'])
                    .factory('ATP', function ($websocket) {
                        // Open a WebSocket connection
                        var ws = $websocket("ws://" + document.location.host + 
                              document.location.pathname + "atpendpoint");
                        var atp = [];

                        ws.onMessage(function (event) {
                            console.log('message: ', event.data);
                            var response;
                            try {
                                response = angular.fromJson(event.data);
                            } catch (e) {
                                document.getElementById("helloId").innerHTML = 
                                                                                   "Sorry, connection failed ...";
                                document.getElementById("btnAtpId").disabled = false;
                                console.log('error: ', e);
                                response = {'error': e};
                            }

                            if (response.hello) {
                                document.getElementById("helloId").innerHTML = response.hello;
                                document.getElementById("btnAtpId").disabled = false;
                            } else {
                                for (var i = 0; i < response.length; i++) {
                                    atp.push({
                                        rank: response[i].rank,
                                        name: response[i].name,
                                        email: response[i].email
                                    });
                                }
                            }
                        });
                        ws.onError(function (event) {
                            console.log('connection Error', event);
                        });
                        ws.onClose(function (event) {
                            console.log('connection closed', event);
                        });
                        ws.onOpen(function () {
                            console.log('connection open');
                            ws.send('HELLO SERVER');
                        });

                        return {
                            atp: atp,
                            status: function () {
                                return ws.readyState;
                            },
                            send: function (message) {
                                if (angular.isString(message)) {
                                    ws.send(message);
                                }
                                else if (angular.isObject(message)) {
                                    ws.send(JSON.stringify(message));
                                }
                            }
                        };
                    })
                    .controller('atpController', function ($scope, ATP) {
                        $scope.ATP = ATP;

                        $scope.submit = function () {
                            ATP.send("ATP SERVER");
                        };                                               
                    });
        </script>
    </body>
</html>


marți, 30 decembrie 2014

Angular JS - Use ng-src and ng-href instead of src and href

The data binding to an <img> or <a> tag, using {{ }} in the src or href  attributes will not work well. Browsers load images in the same time with other content, so Angular cannot resolve data binding requests. So, when you need to use src or href, you better use the Angular, ng-src, and ng-href. Below, is a simple example:

<!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("atpModule", [])
                .controller("atpCtrl", function ($scope) {              
                    $scope.atp = [
                        { photo: 'rafa.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Rafael-Nadal.aspx' },
                        { photo: 'novak.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Novak-Djokovic.aspx' },
                        { photo: 'roger.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Roger-Federer.aspx' },
                        { photo: 'stan.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Stan-Wawrinka.aspx' },
                        { photo: 'david.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/David-Ferrer.aspx' },
                        { photo: 'tonga.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Jo-Wilfried-Tsonga.aspx' },
                        { photo: 'simon.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Gilles-Simon.aspx' },
                        { photo: 'lopez.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Feliciano-Lopez.aspx' },
                        { photo: 'julien.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Julien-Benneteau.aspx' },
                        { photo: 'verdasco.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Fernando-Verdasco.aspx' },
                        { photo: 'mayer.png',
                           weburl: 'http://www.atpworldtour.com/Tennis/Players/Top-Players/Leonardo-Mayer.aspx' }
                    ];                
                });
    </script>
</head>
<body>
   <div ng-app="atpModule" ng-controller="atpCtrl">                
     <div ng-repeat="item in atp">
       <div style="float: left;">
         <a ng-href="{{item.weburl}}">
            <img ng-src="./images/{{item.photo}}" width="100" height="100">
         </a>
        </div>
     </div>
  </div>
</body>
</html>


luni, 29 decembrie 2014

Angular JS - Conditional enable/disable checkboxes

In this post you can see an approach for conditionally enabling/disabling a set of checkboxes. For this we can use the ng-disabled directive and some CSS clases of type className-true and className-false:

<!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"/>
    <style>
        .check-disabled-true {
            color: gray
        }

        .check-disabled-false {
            color: black
        }
    </style>
    <script>
        angular.module("atpModule", [])
                .controller("atpCtrl", function ($scope) {
                    $scope.selectedPrizemoney = 'Select one prize money';
                    $scope.isdisabled=true;
                    $scope.atp = [
                        { name: 'Nadal, Rafael (ESP)', rank: 1, age: '28', prizemoney: 66149345 },
                        { name: 'Djokovic, Novak (SRB)', rank: 2, age: '27', prizemoney: 70704129 },
                        { name: 'Federer, Roger (SUI)', rank: 3, age: '33', prizemoney: 84827704 },
                        { name: 'Wawrinka, Stan (SUI)', rank: 4, age: '29', prizemoney: 13155060 },
                        { name: 'Ferrer, David (ESP)', rank: 5, age: '32', prizemoney: 24034072 },
                        { name: 'Tsonga, Jo-Wilfried (FRA)', rank: 11, age: '29', prizemoney: 1708240 },
                        { name: 'Simon, Gilles (FRA)', rank: 26, age: '29', prizemoney: 760469 },
                        { name: 'Lopez, Feliciano (ESP)', rank: 20, age: '33', prizemoney: 1100579 },
                        { name: 'Benneteau, Julien (FRA)', rank: 28, age: '32', prizemoney: 617688 },
                        { name: 'Verdasco, Fernando (ESP)', rank: 33, age: '30', prizemoney: 689219 },
                        { name: 'Mayer, Leonardo (ARG)', rank: 25, age: '27', prizemoney: 946294 }
                    ];

                    $scope.shouldBeDisabled = function (item) {
                        if (item.prizemoney <= $scope.selectedPrizemoney) {                          
                            return true;
                        } else {                          
                            return false;
                        }
                    };
                });
    </script>
</head>
<body>
<div ng-app="atpModule" ng-controller="atpCtrl">

    <div id="atpPanel" class="panel">
        <h4 class="panel-header">ENABLE/DISABLE CHECKBOXES USING ANGULAR JS</h4>
        <hr/>
        <h5 class="panel-header">Select the maximum prize money:</h5>
        <select ng-model="selectedPrizemoney">
            <option>Select one prize money</option>
            <option ng-repeat="item in atp">{{item.prizemoney}}</option>
        </select>
        <hr/>
        <div ng-repeat="item in atp">
            <p class="check-disabled-{{shouldBeDisabled(item)}}">
                <input type="checkbox" name="{{item.name}}" 
                     value="{{item.name}}" ng-disabled="shouldBeDisabled(item)">{{item.name}}
            </p>
        </div>
    </div>
</div>
</body>
</html>