Extending an AngularJS Widget

Learn what are the possible ways to extend the AngularJS-based widget with some advanced features.

Context

Some of the code snippets boxes in this tutorial may contain commented ellipsis (i.e. // ...). This means that the part of code that has not changed was omitted and only the changes are displayed in the current box. In a such situation, the code snippet provided should be added to the already existing and/or some altering is required.

The steps in this tutorial base on the steps described in the Creating an AngularJS Widget. Once we have created the AngularJS widget in the custom extension, we would like to extend the widget's capabilities by introducing new features.

Managing Serialization/Deserialization

It is possible to adjust the AngularJS widget so that it performs additional logic.

Context

The aim is that the widget sends some statistics through its output socket. Statistics should be divided between different type codes.

Procedure

  1. First, define the statistics themselves.
    1. Create the SearchStatistics class:

      angularCNG/backoffice/src/example/cng/angular/model/SearchStatistics.java

      package example.cng.angular.model;
      
      import java.util.HashMap;
      import java.util.Map;
      
      public class SearchStatistics {
      
          private final Map<String, TypeSearchStatistics> stats;
      
          public SearchStatistics() {
              this.stats = new HashMap<>();
          }
      
          public TypeSearchStatistics getStatistics(final String typeCode) {
              TypeSearchStatistics result = this.stats.get(typeCode);
              if (result == null) {
                  this.stats.put(typeCode, result = new TypeSearchStatistics(typeCode));
              }
              return result;
          }
      
      }
    2. Create the TypeSearchStatistics class:

      angularCNG/backoffice/src/example/cng/angular/model/TypeSearchStatistics.java

      package example.cng.angular.model;
      
      public class TypeSearchStatistics {
      
          private final String typeCode;
      
          private int count;
      
          public TypeSearchStatistics(final String typeCode) {
              this.typeCode = typeCode;
          }
      
          public String getTypeCode() {
              return typeCode;
          }
      
          public int getCount() {
              return count;
          }
      
          public void reset() {
              this.count = 0;
          }
      
          public void inc() {
              inc(1);
          }
      
          public void inc(final int count) {
              this.count += count;
          }
      }
  2. Now, add a new socket to the widget's definition:

    angularCNG/backoffice/resources/widgets/angularwidget/definition.xml

    <widget-definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/widget-definition.xsd"
       id="example.cng.angular.widgets.angularwidget">
    
    	<!-- ... -->
    
    	<sockets>
        	<!-- ... -->
    	    <output id="stats" type="example.cng.angular.model.SearchStatistics" />
    	</sockets>
    </widget-definition>
  3. As the last thing, enable sending these statistics through. What is also the aim here is that all statistics data sent by your widget would be interpreted as implicitly set classes:

    angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.js

    // ...
     
    SampleAngularController = function($scope) {
     
        $scope.socketInput = function(socketId, data) {
     
            // ...
     
            if (data.typeCode) {
                if (!$scope.statistics) {
                    $scope.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
                    $scope.statistics.stats = {};
                }
     
                var stats = $scope.statistics.stats[data.typeCode];
                if (!stats) {
                    stats = {};
                    stats.typeCode = data.typeCode;
                    stats.count = 0;
                    $scope.statistics.stats[data.typeCode] = stats;
                }
                stats.count += 1;       
     
                $scope.adapter.cng().socketEvent("stats", $scope.statistics);
            }
        };
     
    };
     
    // ...
  4. Redeploy the widget and start the server.

Source Files at This Stage - Serialization/Deserialization

You can check the source files at this stage.

See full content of the angularwidget.js

var LEVEL_ERROR = "ERROR";
var LEVEL_WARNING = "Warning";
var LEVEL_INFO = null;
  
showMessage = function (level, message) {
    try {
        if (level === undefined || level == null) {
            alert(message);
        } else {
            alert(level + ": " + message);
        }
    } catch(e) {}
};
  
AngularCNG.init = function(widgetName, controller, services) {
  
    return new AngularCNG( "widgets." + widgetName ).controller(controller, services);
  
};
  
SampleAngularController = function($scope) {
  
    $scope.socketInput = function(socketId, data) {
        showMessage(LEVEL_INFO, "New socket message received");
  
        $scope.input = data;
        $scope.adapter.cng().socketEvent("output", data);
        if (data.typeCode) {
            if (!$scope.statistics) {
                $scope.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
                $scope.statistics.stats = {};
            }
            var stats = $scope.statistics.stats[data.typeCode];
            if (!stats) {
                stats = {};
                stats.typeCode = data.typeCode;
                stats.count = 0;
                $scope.statistics.stats[data.typeCode] = stats;
            }
            stats.count += 1;       
            $scope.adapter.cng().socketEvent("stats", $scope.statistics);
        }
    };
  
};
  
AngularCNG.init("angularwidget", SampleAngularController);

Extending Widget Functionalities

You can extend the AngularJS widget with more functionalities such as enabling localization, model support or configuration, exposing session-related information and enabling additional libraries.

Localization

You can enable localization in the AngularJS widget.

Context

The AngularJS widget you created contains texts that currently are in English only. Backoffice Framework provides a localization functionality that we can use so that the text in the widget was localized respectively to the user language. For more information, see the Localizing UI of the Backoffice Application document).

To achieve localized text, follow the steps:

Procedure

  1. Define labels. The label "Nothing done yet. Waiting for some socket input..." is a general text for all the widgets and should be defined as the global label. In this case, edit global properties files:
    1. In the angularCNG/resources/angularCNG-backoffice-labels/labels.properties file, define:
      label.noinput = Nothing done yet. Waiting for some socket input...
    2. In the angularCNG/resources/angularCNG-backoffice-labels/labels_fr.properties file, define:
      label.noinput = Rien ne s'est passé, j'attends le message...
    3. The rest of the labels are considered as widget-specific and can be defined as follows:

      angularCNG/backoffice/resources/widgets/angularwidget/labels/labels.properties

      label.title.sockets = Below, you may see what has been received through an input socket
      label.title.hello = Hello! This example shows how to write widgets using 3rd party js libraries
      message.socket = New socket message received

      angularCNG/backoffice/resources/widgets/angularwidget/labels/labels_fr.properties

      label.title.sockets=Au-dessous, vous pouvez voir ce qui a été reçu via prise d'entrée.
      label.title.hello=Salut! Cet exemple montre comment écrire widget en utilisant des librairies externes.
      message.socket=Message reçu via prise d'entrée.
  2. Use the labels in the widget view and script files:
    1. Update the HTML file angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html.
      <widget ng-controller="SampleAngularController">
      
      	<h1 cng-local="label.title.hello"></h1> 
      
          <h3 cng-local="label.title.sockets"></h3>
          <div ng-if="!input" cng-global="label.noinput"></div>
          
      	<!-- ... -->
      
       </widget>
    2. Update the Javascript file angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.js.
      SampleAngularController = function($scope) {
      
          $scope.socketInput = function(socketId, data) {
      
              showMessage(LEVEL_INFO, $scope.adapter.cng().local("message.socket"));
      
      		// ...
      	};
      
      	// ...
      
      };
      
      // ...
    3. At this stage, you have a working code. Call ant all, restart the server and refresh the page to see the results. Remember to change language to French when logging in to see how the labels changed.

Source Files at This Stage - Localization

You can check the source files at this stage.

See full content of angularwidget.html

<widget ng-controller="SampleAngularController">
 
    <h1 cng-local="label.title.hello"></h1> 
    <h3 cng-local="label.title.sockets"></h3>
    <div ng-if="!input" cng-global="label.noinput"></div>
    <table ng-if="input">
        <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
            <td class="label">{{key}}</td>
            <td class="value">{{value}}</td>
        </tr>
    </table>
 
    <cng-event type="socket" id="input" handler="socketInput(socket, data)" />
 
</widget>

See full content of angularwidget.js

var LEVEL_ERROR = "ERROR";
var LEVEL_WARNING = "Warning";
var LEVEL_INFO = null;
 
showMessage = function (level, message) {
    try {
        if (level === undefined || level == null) {
            alert(message);
        } else {
            alert(level + ": " + message);
        }
    } catch(e) {}
};
 
AngularCNG.init = function(widgetName, controller, services) {
 
    return new AngularCNG( "widgets." + widgetName ).controller(controller, services);
 
};
 
SampleAngularController = function($scope) {
 
    $scope.socketInput = function(socketId, data) {
        showMessage(LEVEL_INFO, $scope.adapter.cng().local("message.socket"));
 
        $scope.input = data;
        $scope.adapter.cng().socketEvent("output", data);
        if (data.typeCode) {
            if (!$scope.statistics) {
                $scope.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
                $scope.statistics.stats = {};
            }
            var stats = $scope.statistics.stats[data.typeCode];
            if (!stats) {
                stats = {};
                stats.typeCode = data.typeCode;
                stats.count = 0;
                $scope.statistics.stats[data.typeCode] = stats;
            }
            stats.count += 1;        
            $scope.adapter.cng().socketEvent("stats", $scope.statistics);
        }
    };
 
};
 
AngularCNG.init("angularwidget", SampleAngularController);

Enabling Model Support

Enabling model support allows you to apply some changes to an object at runtime and store them in the widget state, avoiding reconfiguration.

Context

At this point, the widget you are currently creating gets any object that comes through the input socket, displays its properties in a table, and sends them over to the output socket. It also gathers some statistics that are being sent through another output socket. You have plugged the AngularJS widget between the AdvancedSearch and the AdvancedSearchEngine widgets and that allows you to see what search conditions have been selected. Now, you would like to be able to alter these conditions. The idea is to allow users to define changes to the object before passing it over. Those changes are to be defined at runtime and stored in the widget state to avoid reconfiguring after running refresh (for more information, see the Storing Data Using Widget Model document). Also, the statistics are to be gathered throughout the widget life-time.

Procedure

  1. Define some more localized labels in the angularCNG/backoffice/resources/widgets/angularwidget/labels/labels.properties:
    ## ...
    
    label.socket.input=Input
    label.socket.output=Output
    
    label.title.model = Here you may see, how a widget integrates with model
    label.model.instruction = Type property name, to change its value
    label.model.commit = Commit change
    label.model.property = Property
    label.model.value = Current value
    label.model.change = New value
    label.model.registered = Registered changes
    message.model = New model received
  2. Now, display the currently defined changes in the widget. Also, you need a form to allow users to define new changes. To show what was actually sent through the output socket, you want to display not only an input object but also output. Therefore, amend the view of our widget in the following way:
    1. Amend HTML file angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html.
      <widget ng-controller="SampleAngularController">
          
      	<!-- ... -->
      
      	<table ng-if="input">
          	<tr>
              	<td class="header" cng-local="label.socket.input"></td>
      	        <td class="header" cng-local="label.socket.output"></td>
          	</tr>
      		<tr>
      			<td>
          			<table>
      			        <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                  			<td class="label">{{key}}</td>
      			            <td class="value">{{value}}</td>
      			        </tr>
      			    </table>
      			</td>
      			<td>
      			    <table>
      			        <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
      			            <td class="label">{{key}}</td>
      			            <td class="value">{{value}}</td>
      			        </tr>
      			    </table>
      			</td>
      		</tr>		
      	</table>
      	<cng-event type="socket" id="input" handler="socketInput(socket, data)" />
      	<hr/>
      
          <h3 class="caption" cng-local="label.title.model"></h3>
          <div cng-local="label.model.registered"></div>
          <table>
              <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
                  <td class="label">{{key}}</td>
                  <td class="value">{{value}}</td>
                  <td ng-click="removeModelChange(key)"><a href="#">X</a></td>
              </tr>
          </table>
          <div cng-local="label.model.instruction"></div>
          <table>
              <tr class="even">
                  <td class="label" cng-local="label.model.property"></td>
                  <td class="value"><input type="text" ng-model="property"></td>
              </tr>
              <tr class="odd">
                  <td class="label" cng-local="label.model.value"></td>
                  <td id="value" class="value">{{input[property]}}</td>
              </tr>
              <tr class="even">
                  <td class="label" cng-local="label.model.change"></td>
                  <td class="value"><input type="text" ng-model="newValue"></td>
              </tr>
              <tr class="odd">
                  <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
              </tr>
          </table>
          
      	<cng-event type="model" handler="modelChanged(model)" />
      
          <hr/>
      
      	<cng-event type="ready" handler="init()" />
      
       </widget>
    2. Amend JavaScript file angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.js.
      // ...
      
      SampleAngularController = function($scope) {
      
          $scope.socketInput = function(socketId, data) {
              showMessage(LEVEL_INFO,  $scope.adapter.cng().local("message.socket"));
      
              $scope.input = jQuery.extend(true, {}, data);
              var changes = $scope.model.changes;
              if (changes) {
                  for(var key in changes) {
                      if (typeof(data[key]) != "undefined") {
                          data[key] = changes[key];
                      }
                  }
              }
      		$scope.output = data;
              $scope.adapter.cng().socketEvent("output", data);
      
      		if (!$scope.model.statistics) {
                  $scope.model.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
                  $scope.model.statistics.stats = {};
              }
              if (data.typeCode) {
                  var stats = $scope.model.statistics.stats[data.typeCode];
                  if (!stats) {
                      stats = {};
                      stats.typeCode = data.typeCode;
                      stats.count = 0;
                      $scope.model.statistics.stats[data.typeCode] = stats;
                  }
                  stats.count += 1;
      
      			$scope.adapter.cng().model("statistics", $scope.model.statistics);
      	        $scope.adapter.cng().socketEvent("stats", $scope.model.statistics); 
      		}  
      	};	
      
      	$scope.modelChanged = function(model) {
              showMessage(LEVEL_WARNING, $scope.adapter.cng().local("message.model"));
      
              $scope.property = null;
              $scope.model = model;
          };
      
          $scope.commitModelChanges = function(key, value) {
              var changes = $scope.model.changes;
              if (!changes) {
                  changes = {};
              }
              changes[key] = value;
      
              $scope.adapter.cng().model('changes', changes);
          };
      
          $scope.removeModelChange = function(key) {
              var changes = $scope.model.changes;
              delete changes[key];
      
              $scope.adapter.cng().model('changes', changes);
          };
      
      	$scope.init = function() {
      		if (!$scope.model) {
      			$scope.model = {};
      		}
              $scope.statistics = $scope.adapter.cng().model("statistics");
      	};
      
      };
      
      // ...

Results

The following figures show how the widget works:

Source Files at This Stage - Model Support

You can check the source files at this stage.

See full content of angularwidget.html

<widget ng-controller="SampleAngularController">
    
	<h1 cng-local="label.title.hello"></h1>

    <h3 cng-local="label.title.sockets"></h3>
    <div ng-if="!input" cng-global="label.noinput"></div>
    <table ng-if="input">
        <tr>
            <td class="header" cng-local="label.socket.input"></td>
            <td class="header" cng-local="label.socket.output"></td>
        </tr>
        <tr>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
        </tr>    
    </table>
    <cng-event type="socket" id="input" handler="socketInput(socket, data)" />
    <hr/>
 
    <h3 class="caption" cng-local="label.title.model"></h3>
    <div cng-local="label.model.registered"></div>
    <table>
        <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
            <td class="label">{{key}}</td>
            <td class="value">{{value}}</td>
            <td ng-click="removeModelChange(key)"><a href="#">X</a></td>
        </tr>
    </table>
    <div cng-local="label.model.instruction"></div>
    <table>
        <tr class="even">
            <td class="label" cng-local="label.model.property"></td>
            <td class="value"><input type="text" ng-model="property"></td>
        </tr>
        <tr class="odd">
            <td class="label" cng-local="label.model.value"></td>
            <td id="value" class="value">{{input[property]}}</td>
        </tr>
        <tr class="even">
            <td class="label" cng-local="label.model.change"></td>
            <td class="value"><input type="text" ng-model="newValue"></td>
        </tr>
        <tr class="odd">
            <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
        </tr>
    </table>
    
	<cng-event type="model" handler="modelChanged(model)" />
    
	<hr/>

    <cng-event type="ready" handler="init()" />

  </widget>

See full content of angularwidget.js

var LEVEL_ERROR = "ERROR";
var LEVEL_WARNING = "Warning";
var LEVEL_INFO = null;

showMessage = function (level, message) {
    try {
        if (level === undefined || level == null) {
            alert(message);
        } else {
            alert(level + ": " + message);
        }
    } catch(e) {}
};

AngularCNG.init = function(widgetName, controller, services) {

    return new AngularCNG( "widgets." + widgetName ).controller(controller, services);

};

SampleAngularController = function($scope) {

    $scope.socketInput = function(socketId, data) {
        showMessage(LEVEL_INFO, $scope.adapter.cng().local("message.socket"));

        $scope.input = jQuery.extend(true, {}, data);
        var changes = $scope.model.changes;
        if (changes) {
            for(var key in changes) {
                if (typeof(data[key]) != "undefined") {
                    data[key] = changes[key];
                }
            }
        }
        $scope.output = data;
        $scope.adapter.cng().socketEvent("output", data);

        if (!$scope.model.statistics) {
            $scope.model.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
            $scope.model.statistics.stats = {};
        }
        if (data.typeCode) {
            var stats = $scope.model.statistics.stats[data.typeCode];
            if (!stats) {
                stats = {};
                stats.typeCode = data.typeCode;
                stats.count = 0;
                $scope.model.statistics.stats[data.typeCode] = stats;
            }
            stats.count += 1;

            $scope.adapter.cng().model("statistics", $scope.model.statistics);
            $scope.adapter.cng().socketEvent("stats", $scope.model.statistics);
        } 
    }; 
 
    $scope.modelChanged = function(model) {
        showMessage(LEVEL_WARNING, $scope.adapter.cng().local("message.model"));

        $scope.property = null;
        $scope.model = model;
    };

    $scope.commitModelChanges = function(key, value) {
        var changes = $scope.model.changes;
        if (!changes) {
            changes = {};
        }
        changes[key] = value;

        $scope.adapter.cng().model('changes', changes);
    };

    $scope.removeModelChange = function(key) {
        var changes = $scope.model.changes;
        delete changes[key];

        $scope.adapter.cng().model('changes', changes);
    };

    $scope.init = function() {
        if (!$scope.model) {
            $scope.model = {};
        }
        $scope.statistics = $scope.adapter.cng().model("statistics");
    };

};

AngularCNG.init("angularwidget", SampleAngularController);

Enabling Widget Configuration

Enabled widget configuration allows you to have several instances of the same widget and each of them can behave a bit differently.

Context

At this point, you have a widget that reads data from the input socket, displays what was read, changes some values, and passes them through to the output socket. What you are to achieve now is that if the widget is used in several places in the Backoffice Administration Cockpit application, it should be configurable at runtime only in a few of them. This means that you need to add some configuration informing the widget whether to show the model editing form or not. Also, if you don't allow users to define changes, you need to allow to create such a definition offline (at the design level).

Procedure

  1. Add a condition when to display the form in the view file of our widget. Amend the angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html file as follows:
    <widget ng-controller="SampleAngularController">
        
    	<!-- ... -->
    
    	<table>
        	<tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
        	    <td class="label">{{key}}</td>
        	    <td class="value">{{value}}</td>
        	    <td ng-if="settings && settings.enableModelEditing" ng-click="removeModelChange(key)"><a href="#">X</a></td>
    	    </tr>
    	</table>
    	<div ng-if="settings && settings.enableModelEditing">
    		    	
    		<!-- ... -->
    
    	</div>
    
    	<cng-event type="model" handler="modelChanged(model)" />
    
    	<hr/>
    	
    	<!--- ... -->
    
    </widget>
  2. To see how these changes work, reconfigure the widget. Press F4 (or fn + F4 on Unix system) to enter the Application Orchestrator mode and add a setting to the Angular Sample Widget called enableModelEditing of type java.lang.Boolean:
  3. You are now able to enable/disable runtime configuration of our widget. At this stage, enable design-time configuration. Parse the configuration parameter and rewrite its value to the widget model – all of this right after the widget is loaded:

    Amend the angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.js file as follows:

    SampleAngularController = function($scope) {
    
    	// ...
    
    	$scope.init = function() {
    
    		// ...
    
    		var settings = $scope.settings["initialChanges"];
            if (settings && !$scope.model.changes) {
                var changes = JSON.parse(settings);
                $scope.model.changes = changes;
                $scope.helper.cockpit().model("changes", changes);
            }
    	}
    
     };
    
    // ...
  4. Define the settings and their default values in the widget definition.xml:

    Amend the angularCNG/backoffice/resources/widgets/AngularWidget/definition.xml file as follows:

    <widget-definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/widget-definition.xsd"
       id="example.cng.jscng.widgets.angularwidget">
       
    	<!-- ... -->
    
    	<settings>
        	<setting key="enableModelEditing" type="java.lang.Boolean" default-value="false"/>
        	<setting key="initialChanges" type="java.lang.String" default-value="{ &quot;globalOperator&quot; : &quot;AND&quot; }"/>
    	</settings>
    
    </widget-definition>

Source Files at This Stage - Widget Configuration

You can check the source files at this stage.

See full content of angularwidget.html

<widget ng-controller="SampleAngularController">
 
    <h1 cng-local="label.title.hello"></h1>
 
    <h3 cng-local="label.title.sockets"></h3>
    <div ng-if="!input" cng-global="label.noinput"></div>
    <table ng-if="input">
        <tr>
            <td class="header" cng-local="label.socket.input"></td>
            <td class="header" cng-local="label.socket.output"></td>
        </tr>
        <tr>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
        </tr>    
    </table>
    <cng-event type="socket" id="input" handler="socketInput(socket, data)" />
    <hr/>
 
    <h3 class="caption" cng-local="label.title.model"></h3>
    <div cng-local="label.model.registered"></div>
    <table>
        <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
            <td class="label">{{key}}</td>
            <td class="value">{{value}}</td>
            <td ng-if="settings && settings.enableModelEditing" ng-click="removeModelChange(key)"><a href="#">X</a></td>
        </tr>
    </table>
    <div ng-if="settings && settings.enableModelEditing">
    <div cng-local="label.model.instruction"></div>
    <table>
        <tr class="even">
            <td class="label" cng-local="label.model.property"></td>
            <td class="value"><input type="text" ng-model="property"></td>
        </tr>
        <tr class="odd">
            <td class="label" cng-local="label.model.value"></td>
            <td id="value" class="value">{{input[property]}}</td>
        </tr>
        <tr class="even">
            <td class="label" cng-local="label.model.change"></td>
            <td class="value"><input type="text" ng-model="newValue"></td>
        </tr>
        <tr class="odd">
            <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
        </tr>
    </table>
	</div>
     
    <cng-event type="model" handler="modelChanged(model)" />
 
    <hr/>
 
    <cng-event type="ready" handler="init()" />
 
  </widget>

See full content of angularwidget.js

var LEVEL_ERROR = "ERROR";
var LEVEL_WARNING = "Warning";
var LEVEL_INFO = null;
 
showMessage = function (level, message) {
    try {
        if (level === undefined || level == null) {
            alert(message);
        } else {
            alert(level + ": " + message);
        }
    } catch(e) {}
};
 
AngularCNG.init = function(widgetName, controller, services) {
 
    return new AngularCNG( "widgets." + widgetName ).controller(controller, services);
 
};
 
SampleAngularController = function($scope) {
 
    $scope.socketInput = function(socketId, data) {
        showMessage(LEVEL_INFO, $scope.adapter.cng().local("message.socket"));
 
        $scope.input = jQuery.extend(true, {}, data);
        var changes = $scope.model.changes;
        if (changes) {
            for(var key in changes) {
                if (typeof(data[key]) != "undefined") {
                    data[key] = changes[key];
                }
            }
        }
        $scope.output = data;
        $scope.adapter.cng().socketEvent("output", data);
 
        if (!$scope.model.statistics) {
            $scope.model.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
            $scope.model.statistics.stats = {};
        }
        if (data.typeCode) {
            var stats = $scope.model.statistics.stats[data.typeCode];
            if (!stats) {
                stats = {};
                stats.typeCode = data.typeCode;
                stats.count = 0;
                $scope.model.statistics.stats[data.typeCode] = stats;
            }
            stats.count += 1;
 
            $scope.adapter.cng().model("statistics", $scope.model.statistics);
            $scope.adapter.cng().socketEvent("stats", $scope.model.statistics);
        } 
    }; 
 
    $scope.modelChanged = function(model) {
        showMessage(LEVEL_WARNING, $scope.adapter.cng().local("message.model"));
 
        $scope.property = null;
        $scope.model = model;
    };
 
    $scope.commitModelChanges = function(key, value) {
        var changes = $scope.model.changes;
        if (!changes) {
            changes = {};
        }
        changes[key] = value;
 
        $scope.adapter.cng().model('changes', changes);
    };
 
    $scope.removeModelChange = function(key) {
        var changes = $scope.model.changes;
        delete changes[key];
 
        $scope.adapter.cng().model('changes', changes);
    };
 
    $scope.init = function() {
        if (!$scope.model) {
            $scope.model = {};
        }
        $scope.statistics = $scope.adapter.cng().model("statistics");
        
        var settings = $scope.settings["initialChanges"];
        if (settings && !$scope.model.changes) {
            var changes = JSON.parse(settings);
            $scope.model.changes = changes;
            $scope.helper.cockpit().model("changes", changes);
        }    
    };
 
};
 
AngularCNG.init("angularwidget", SampleAngularController);

See full content of definition.xml

<widget-definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/widget-definition.xsd"
   id="example.cng.angular.widgets.angularwidget">
    <name>Angular Sample Widget</name>
    <description>Sample widget using AngularJS</description>
    <defaultTitle>AngularJS Sample Widget</defaultTitle>
    <author>hybris</author>
    <version>1.0</version>
    <view src="angularwidget.html" />
    <keywords>
        <keyword>AngularJS</keyword>
    </keywords>
    <sockets>
        <input id="input" type="java.lang.Object" />
        <output id="output" type="&lt;T&gt;" />
        <output id="stats" type="example.cng.angular.model.SearchStatistics" />
    </sockets>
    
    <settings>
        <setting key="enableModelEditing" type="java.lang.Boolean" default-value="false"/>
        <setting key="initialChanges" type="java.lang.String" default-value="{ &quot;globalOperator&quot; : &quot;AND&quot; }"/>
    </settings>
    
</widget-definition>

Exposing Session-Related Information in Widget

To polish your widget, you need to add a few things: administrator privileges, user's name and custom session properties.

Procedure

  1. Widget should allow editing model changes, independently of its settings, if a user currently logged in has the administration privileges. Change the condition in the angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html: as follows:
    <widget ng-controller="SampleAngularController">
        
    	<!-- ... -->
    
    	<table>
        	<tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
        	    
    			<!-- ... --->
    
        	    <td ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin" ng-click="removeModelChange(key)"><a href="#">X</a></td>
    	    </tr>
    	</table>
    	<div ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin">
    		    	
    		<!-- ... -->
    
    	</div>
    	
    	<!--- ... -->
    
    </widget>
    Source Files at This Stage

    See full content of angularwidget.html

    <widget ng-controller="SampleAngularController">
     
        <h1 cng-local="label.title.hello"></h1>
     
        <h3 cng-local="label.title.sockets"></h3>
        <div ng-if="!input" cng-global="label.noinput"></div>
        <table ng-if="input">
            <tr>
                <td class="header" cng-local="label.socket.input"></td>
                <td class="header" cng-local="label.socket.output"></td>
            </tr>
            <tr>
                <td>
                    <table>
                        <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                            <td class="label">{{key}}</td>
                            <td class="value">{{value}}</td>
                        </tr>
                    </table>
                </td>
                <td>
                    <table>
                        <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
                            <td class="label">{{key}}</td>
                            <td class="value">{{value}}</td>
                        </tr>
                    </table>
                </td>
            </tr>    
        </table>
        <cng-event type="socket" id="input" handler="socketInput(socket, data)" />
        <hr/>
     
        <h3 class="caption" cng-local="label.title.model"></h3>
        <div cng-local="label.model.registered"></div>
        <table>
            <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
                <td class="label">{{key}}</td>
                <td class="value">{{value}}</td>
                <td ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin" ng-click="removeModelChange(key)"><a href="#">X</a></td>
            </tr>
        </table>
        <div ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin">
        <div cng-local="label.model.instruction"></div>
        <table>
            <tr class="even">
                <td class="label" cng-local="label.model.property"></td>
                <td class="value"><input type="text" ng-model="property"></td>
            </tr>
            <tr class="odd">
                <td class="label" cng-local="label.model.value"></td>
                <td id="value" class="value">{{input[property]}}</td>
            </tr>
            <tr class="even">
                <td class="label" cng-local="label.model.change"></td>
                <td class="value"><input type="text" ng-model="newValue"></td>
            </tr>
            <tr class="odd">
                <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
            </tr>
        </table>
        </div>
         
        <cng-event type="model" handler="modelChanged(model)" />
     
        <hr/>
     
        <cng-event type="ready" handler="init()" />
     
      </widget>
  2. Personalize the widget by adding the current user's name to one of captions in the angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html:
    <widget ng-controller="SampleAngularController">
        
    	<h1 class="caption" cng-local="label.title.hello"></h1>
    
    	<h3 class="caption">{{sessionInfo.currentUser}}! {{adapter.cng().local('label.title.sockets')}}</h3>
    	
    	<!--- ... -->
    
    </widget>
    Source Files at This Stage

    See full content of angularwidget.html

    <widget ng-controller="SampleAngularController">
     
        <h1 class="caption" cng-local="label.title.hello"></h1>
        <h3 class="caption">{{sessionInfo.currentUser}}! {{adapter.cng().local('label.title.sockets')}}</h3>
        <div ng-if="!input" cng-global="label.noinput"></div>
        <table ng-if="input">
            <tr>
                <td class="header" cng-local="label.socket.input"></td>
                <td class="header" cng-local="label.socket.output"></td>
            </tr>
            <tr>
                <td>
                    <table>
                        <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                            <td class="label">{{key}}</td>
                            <td class="value">{{value}}</td>
                        </tr>
                    </table>
                </td>
                <td>
                    <table>
                        <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
                            <td class="label">{{key}}</td>
                            <td class="value">{{value}}</td>
                        </tr>
                    </table>
                </td>
            </tr>    
        </table>
        <cng-event type="socket" id="input" handler="socketInput(socket, data)" />
        <hr/>
     
        <h3 class="caption" cng-local="label.title.model"></h3>
        <div cng-local="label.model.registered"></div>
        <table>
            <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
                <td class="label">{{key}}</td>
                <td class="value">{{value}}</td>
                <td ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin" ng-click="removeModelChange(key)"><a href="#">X</a></td>
            </tr>
        </table>
        <div ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin">
        <div cng-local="label.model.instruction"></div>
        <table>
            <tr class="even">
                <td class="label" cng-local="label.model.property"></td>
                <td class="value"><input type="text" ng-model="property"></td>
            </tr>
            <tr class="odd">
                <td class="label" cng-local="label.model.value"></td>
                <td id="value" class="value">{{input[property]}}</td>
            </tr>
            <tr class="even">
                <td class="label" cng-local="label.model.change"></td>
                <td class="value"><input type="text" ng-model="newValue"></td>
            </tr>
            <tr class="odd">
                <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
            </tr>
        </table>
        </div>
         
        <cng-event type="model" handler="modelChanged(model)" />
     
        <hr/>
     
        <cng-event type="ready" handler="init()" />
     
      </widget>
  3. As the current user name isn't descriptive enough, you can display also actual user's name. To do this, add a session info decorator.
    1. Create the decorator class, UserNameSessionDecorator:

      angularCNG/backoffice/src/example/cng/angular/session/UserNameSessionDecorator.java

      package example.cng.angular.session;
      
      import com.hybris.cockpitng.util.js.JsWidgetSessionDTO;
      import com.hybris.cockpitng.util.js.JsWidgetSessionInfoDecorator;
      import de.hybris.platform.servicelayer.user.UserService;
      import org.springframework.beans.factory.annotation.Required;
      
      public class UserNameSessionDecorator implements JsWidgetSessionInfoDecorator {
      
          private UserService userService;
      
          @Override
          public JsWidgetSessionDTO decorate(final JsWidgetSessionDTO dto) {
              dto.addCustomAttribute("name", getUserService().getCurrentUser().getDisplayName());
              return dto;
          }
      
          public UserService getUserService() {
              return userService;
          }
      
          @Required
          public void setUserService(final UserService userService) {
              this.userService = userService;
          }
      }
    2. Register it as a Spring bean and populate it with the extender. Amend the angularCNG/resources/angularCNG-backoffice-spring.xml file as follows:
      <beans xmlns="http://www.springframework.org/schema/beans"
      	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xsi:schemaLocation="http://www.springframework.org/schema/beans
                 http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      	<!-- ... -->
      
          <bean id="userNameSessionDecorator" class="example.cng.angular.session.UserNameSessionDecorator">
              <property name="userService" ref="userService" />
          </bean>
      
          <bean parent="abstractJsWidgetSessionInfoCollectorExtender" lazy-init="false" init-method="extend" destroy-method="clean">
              <property name="additionalValues">
                  <list merge="true" value-type="com.hybris.cockpitng.util.js.JsWidgetSessionInfoDecorator">
                      <ref bean="userNameSessionDecorator" />
                  </list>
              </property>
          </bean>
      
      </beans>
    3. Display this custom session property in the widget by amending the angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html as follows:
      <widget ng-controller="SampleAngularController">
          
      	<h1 class="caption" cng-local="label.title.hello"></h1>
      
      	<h3 class="caption">{{sessionInfo.customAttributes['name']}} ({{sessionInfo.currentUser}})! {{adapter.cng().local('label.title.sockets')}}</h3>
      	
      	<!--- ... -->
      
      </widget>

Results

As a result of this configuration, we have the session-related information displayed in our widget:

Source Files at This Stage - Session-Related Info

You can check the source files at this stage.

See full content of angularCNG-backoffice-spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="angularCNGService" class="example.cng.angular.services.AngularCNGService" />
    <bean id="angularCNGLabelLocator" class="com.hybris.cockpitng.util.labels.ResourcesLabelLocator" scope="singleton" init-method="init" lazy-init="false">
        <property name="location" value="/angularCNG-backoffice-labels/"/>
        <property name="name" value="labels"/>
    </bean>
    
    <bean id="typeSearchStatisticsObjectMapperFactory" class="example.cng.angular.json.TypeSearchStatisticsMapperConfiguration" />
 
    <bean parent="abstractJSONMapperExtender" lazy-init="false" init-method="extend" destroy-method="clean">
        <property name="additionalValues">
            <list merge="true" value-type="com.hybris.cockpitng.json.ObjectMapperConfiguration">
                <ref bean="typeSearchStatisticsObjectMapperFactory" />
            </list>
        </property>
    </bean>
    
    <bean id="userNameSessionDecorator" class="example.cng.angular.session.UserNameSessionDecorator">
        <property name="userService" ref="userService" />
    </bean>
    <bean parent="abstractJsWidgetSessionInfoCollectorExtender" lazy-init="false" init-method="extend" destroy-method="clean">
        <property name="additionalValues">
            <list merge="true" value-type="com.hybris.cockpitng.util.js.JsWidgetSessionInfoDecorator">
                <ref bean="userNameSessionDecorator" />
            </list>
        </property>
    </bean>
</beans>

See full content of angularwidget.html

<widget ng-controller="SampleAngularController">
 
    <h1 class="caption" cng-local="label.title.hello"></h1>
    <h3 class="caption">{{sessionInfo.customAttributes['name']}} ({{sessionInfo.currentUser}})! {{adapter.cng().local('label.title.sockets')}}</h3>
    <div ng-if="!input" cng-global="label.noinput"></div>
    <table ng-if="input">
        <tr>
            <td class="header" cng-local="label.socket.input"></td>
            <td class="header" cng-local="label.socket.output"></td>
        </tr>
        <tr>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
        </tr>    
    </table>
    <cng-event type="socket" id="input" handler="socketInput(socket, data)" />
    <hr/>
 
    <h3 class="caption" cng-local="label.title.model"></h3>
    <div cng-local="label.model.registered"></div>
    <table>
        <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
            <td class="label">{{key}}</td>
            <td class="value">{{value}}</td>
            <td ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin" ng-click="removeModelChange(key)"><a href="#">X</a></td>
        </tr>
    </table>
    <div ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin">
    <div cng-local="label.model.instruction"></div>
    <table>
        <tr class="even">
            <td class="label" cng-local="label.model.property"></td>
            <td class="value"><input type="text" ng-model="property"></td>
        </tr>
        <tr class="odd">
            <td class="label" cng-local="label.model.value"></td>
            <td id="value" class="value">{{input[property]}}</td>
        </tr>
        <tr class="even">
            <td class="label" cng-local="label.model.change"></td>
            <td class="value"><input type="text" ng-model="newValue"></td>
        </tr>
        <tr class="odd">
            <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
        </tr>
    </table>
    </div>
     
    <cng-event type="model" handler="modelChanged(model)" />
 
    <hr/>
 
    <cng-event type="ready" handler="init()" />
 
  </widget>

Enabling Libraries

Some of the script included in the angularwidget.js is not actually widget-related, rather it's more library-like code. You may then move it to a separate file, which could be used by other widgets.

Procedure

  1. Create a library that could be used by any other widget and/or extension. Remove the following code snippet from the angularwidget.js file and create a library file out of it:

    angularCNG/resources/cockpitng/cng/alerts.js

    var LEVEL_ERROR = "ERROR";
    var LEVEL_WARNING = "Warning";
    var LEVEL_INFO = null;
    
    showMessage = function (level, message) {
    	try {
    		if (level === undefined || level == null) {
    	        alert(message);
    	    } else {
    	        alert(level + ": " + message);
    	    }
    	} catch(e) {}
    };
  2. Create another library that should be available only for the widgets from the current extension. Remove the below snippet from the angularwidget.js file and defining the new library out of it:

    angularCNG/backoffice/resources/cng/js/widgets-angular.js

    AngularCNG.init = function(widgetName, controller, services) {
    
        return new AngularCNG( "widgets." + widgetName ).controller(controller, services);
    
    };
  3. Now that you have created the relevant libraries, add a dependency to them. This is done in the angularCNG/backoffice/resources/cng/js/js-libraries.xml file:
    <libraries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/libraries.xsd">
    
    	<!- ... -->
    
    	<library protocol="RESOURCE" url="widgets-angular.js" /> <!-- this is a local library for extension-only -->
    
        <library protocol="CLASSPATH" url="alerts.js" /> <!-- this a dependency that could be defined by any other extension -->
    
    </libraries>

Source Files at This Stage - Libraries

You can check the source files at this stage.

See full content of js-libraries.xml

<libraries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/libraries.xsd">
 
    <library>
        <name>angular</name>
    </library>
    
    <library protocol="RESOURCE" url="widgets-angular.js" /> 
    
    <library protocol="CLASSPATH" url="alerts.js" /> 
 
</libraries>

Summary

As a final result, you get a fully working widget written in AngularJS:

Sources

Here are the final full source files used in configuration of the AngularJS widget.

angularCNG/backoffice/resources/cng/js/js-libraries.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<libraries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/libraries.xsd">

    <library url="/angularjs/1.3.16/angular.min.js" protocol="RESOURCE">
        <name>angular.min</name>
        <version>1.3.16</version>
    </library>

    <!-- this is a local library for extension-only use -->
    <library protocol="RESOURCE" url="widgets-angular.js" />
    <!-- this is a dependency that can be defined by any other extension -->
    <library protocol="CLASSPATH" url="alerts.js" />
</libraries>

angularCNG/backoffice/resources/widgets/angularwidget/definition.xml

<widget-definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/widget-definition.xsd"
                   id="example.cng.angular.widgets.angularwidget">
    <name>AngularJS Sample Widget</name>
    <description>Sample widget using AngularJS</description>
    <defaultTitle>AngularJS Sample Widget</defaultTitle>
    <author>hybris</author>
    <version>1.0</version>
    <view src="angularwidget.html" />
    <keywords>
        <keyword>AngularJS</keyword>
    </keywords>
    <sockets>
        <input id="input" type="java.lang.Object" />
        <output id="output" type="&lt;T&gt;" />
        <output id="stats" type="example.cng.angular.model.SearchStatistics" />
    </sockets>
    <settings>
        <setting key="enableModelEditing" type="java.lang.Boolean" default-value="false"/>
        <setting key="initialChanges" type="java.lang.String" default-value="{ &quot;globalOperator&quot; : &quot;AND&quot; }"/>
    </settings>
</widget-definition>

angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.html

<widget ng-controller="SampleAngularController">

    <h1 class="caption" cng-local="label.title.hello"></h1>

    <h3 class="caption">{{sessionInfo.customAttributes['name']}} ({{sessionInfo.currentUser}})! {{adapter.cng().local('label.title.sockets')}}</h3>
    <div ng-if="!input" cng-global="label.noinput"></div>
    <table ng-if="input">
        <tr>
            <td class="header" cng-local="label.socket.input"></td>
            <td class="header" cng-local="label.socket.output"></td>
        </tr>
        <tr>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in input" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
            <td>
                <table>
                    <tr ng-repeat="(key, value) in output" ng-class="{true:'even', false:'odd'}[$even]">
                        <td class="label">{{key}}</td>
                        <td class="value">{{value}}</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

    <cng-event type="socket" id="input" handler="socketInput(socket, data)" />

    <hr/>

    <h3 class="caption" cng-local="label.title.model"></h3>
    <div cng-local="label.model.registered"></div>
    <table>
        <tr ng-repeat="(key, value) in model.changes" ng-class="{true:'even', false:'odd'}[$even]">
            <td class="label">{{key}}</td>
            <td class="value">{{value}}</td>
            <td ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin" ng-click="removeModelChange(key)"><a href="#">X</a></td>
        </tr>
    </table>
    <div ng-if="(settings && settings.enableModelEditing) || sessionInfo.admin">
        <div cng-local="label.model.instruction"></div>
        <table>
            <tr class="even">
                <td class="label" cng-local="label.model.property"></td>
                <td class="value"><input type="text" ng-model="property"></td>
            </tr>
            <tr class="odd">
                <td class="label" cng-local="label.model.value"></td>
                <td id="value" class="value">{{input[property]}}</td>
            </tr>
            <tr class="even">
                <td class="label" cng-local="label.model.change"></td>
                <td class="value"><input type="text" ng-model="newValue"></td>
            </tr>
            <tr class="odd">
                <td colspan="2" class="commit"><button type="button" ng-click="commitModelChanges(property, newValue)" cng-local="label.model.commit"/></td>
            </tr>
        </table>
    </div>

    <cng-event type="model" handler="modelChanged(model, property)" />

    <hr/>

    <cng-event type="ready" handler="init()" />

</widget>

angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.js

SampleAngularController = function($scope) {

    $scope.socketInput = function(socketId, data) {
        showMessage(LEVEL_INFO,  $scope.adapter.cng().local("message.socket"));
        $scope.input = jQuery.extend(true, {}, data);
        var changes = $scope.model.changes;
        if (changes) {
            for(var key in changes) {
                if (typeof(data[key]) != "undefined") {
                    data[key] = changes[key];
                }
            }
        }
        $scope.output = data;
        $scope.adapter.cng().socketEvent("output", data);

        if (!$scope.model.statistics) {
            $scope.model.statistics = { $class: "example.cng.angular.model.SearchStatistics"}; // Notice! We explicitly point a Java class
        }
        if (!$scope.model.statistics.stats) {
            $scope.model.statistics.stats = {};
        }
        if (data.typeCode) {
            var stats = $scope.model.statistics.stats[data.typeCode];
            if (!stats) {
                stats = {};
                stats.typeCode = data.typeCode;
                stats.count = 0;
                $scope.model.statistics.stats[data.typeCode] = stats;
            }
            stats.count += 1;
            $scope.adapter.cng().model("statistics", $scope.model.statistics);
            $scope.adapter.cng().socketEvent("stats", $scope.model.statistics);
        }
    };

    $scope.modelChanged = function(model, property) {
        showMessage(LEVEL_WARNING, $scope.adapter.cng().local("message.model") + ": " + property);
        
		$scope.property = null;
        $scope.newValue = null;
        $scope.model = model;
    };

    $scope.commitModelChanges = function(key, value) {
        var changes = $scope.model.changes;
        if (!changes) {
            changes = {};
        }
        changes[key] = value;
        $scope.adapter.cng().model('changes', changes);
    };

    $scope.removeModelChange = function(key) {
        var changes = $scope.model.changes;
        delete changes[key];
        $scope.adapter.cng().model('changes', changes);
    };

    $scope.init = function() {
        if (!$scope.model) {
            $scope.model = {};
        }
        $scope.statistics = $scope.adapter.cng().model("statistics");
        
		var settings = $scope.settings["initialChanges"];
        if (settings && !$scope.model.changes) {
            var changes = JSON.parse(settings);
            $scope.model.changes = changes;
            $scope.adapter.cng().model("changes", changes);
        }
    };

};

AngularCNG.init("angularwidget", SampleAngularController);

angularCNG/resources/cockpitng/cng/alerts.js

var LEVEL_ERROR = "ERROR";
var LEVEL_WARNING = "Warning";
var LEVEL_INFO = null;

showMessage = function (level, message) {
	try {
		if (level === undefined || level == null) {
        	alert(message);
	    } else {
    	    alert(level + ": " + message);
    	}
	} catch(e) {}
};

angularCNG/backoffice/resources/cng/js/widgets-angular.js

AngularCNG.init = function(widgetName, controller, services) {

    return new AngularCNG( "widgets." + widgetName ).controller(controller, services);

};

angularCNG/backoffice/resources/widgets/angularwidget/labels/labels.properties

label.title.sockets = Below, you may see what has been received through an input socket
label.title.hello = Hello! This example shows how to write widgets using 3rd party js libraries
message.socket = New socket message received

label.socket.input=Input
label.socket.output=Output

label.title.model = Here you may see, how a widget integrates with model
label.model.instruction = Type property name, to change its value
label.model.commit = Commit change
label.model.property = Property
label.model.value = Current value
label.model.change = New value
label.model.registered = Registered changes
message.model = Model changed

angularCNG/resources/angularCNG-backoffice-labels/labels_fr.properties

label.noinput = Rien ne s'est passé, j'attends le message...

angularCNG/backoffice/resources/widgets/angularwidget/labels/labels_fr.properties

label.title.sockets=Au-dessous, vous pouvez voir ce qui a été reçu via prise d'entrée.
label.title.hello=Salut! Cet exemple montre comment écrire widget en utilisant des librairies externes.
message.socket=Message reçu via prise d'entrée.

angularCNG/backoffice/resources/widgets/angularwidget/angularwidget.css

.yw-labelstyle
{
    color: red;
}

.caption {
    font-weight: bold;
    color: #13275a;
}

table {
    border: none;
    margin: 0;
}

.caption {
    font-weight: bold;
    color: #13275a;
}

table .header {
    text-align: center;
    font-weight: bold;
    background-color: #13275a;
    color: #c2e1ef;
}

table .label {
    text-align: right;
}

table .value {
    text-align: left;
}

table .even {
    background-color: #c4c4c4;
}

table .odd {
    background-color: #6699cc;
}

table .commit {
    text-align: center;
}

widget a {
    text-decoration: none;
    color: #303030;
}

widget a:hover {
    text-decoration: underline;
    color: #303030;
}

angularCNG/resources/angularCNG-backoffice-spring.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:cng="http://www.hybris.com/cockpitng/spring"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.hybris.com/cockpitng/spring http://www.hybris.com/cockpitng/spring/cng-spring.xsd">

	<bean id="angularCNGService" class="example.cng.angular.services.AngularCNGService" />

	<bean id="angularCNGLabelLocator" class="com.hybris.cockpitng.util.labels.ResourcesLabelLocator" scope="singleton" init-method="init" lazy-init="false">
  		<property name="location" value="/angularCNG-backoffice-labels/"/>
  		<property name="name" value="labels"/>
  	</bean>

	<bean id="userNameSessionDecorator" class="example.cng.angular.session.UserNameSessionDecorator">
		<property name="userService" ref="userService" />
	</bean>

	<cng:list-extender parent="abstractJsWidgetSessionInfoCollectorExtender" abstract="false">
		<cng:add value-type="com.hybris.cockpitng.util.js.JsWidgetSessionInfoDecorator">
			<ref bean="userNameSessionDecorator" />
		</cng:add>
	</cng:list-extender>
</beans>

angularCNG/backoffice/src/example/cng/angular/model/SearchStatistics.java

package example.cng.angular.model;
 
import java.util.HashMap;
import java.util.Map;
 
public class SearchStatistics {
 
    private final Map<String, TypeSearchStatistics> stats;
 
    public SearchStatistics() {
        this.stats = new HashMap<>();
    }
 
    public TypeSearchStatistics getStatistics(final String typeCode) {
        TypeSearchStatistics result = this.stats.get(typeCode);
        if (result == null) {
            this.stats.put(typeCode, result = new TypeSearchStatistics(typeCode));
        }
        return result;
    }
 
}

angularCNG/backoffice/src/example/cng/angular/model/TypeSearchStatistics.java

package example.cng.angular.model;
 
public class TypeSearchStatistics {
 
    private final String typeCode;
 
    private int count;
 
    public TypeSearchStatistics(final String typeCode) {
        this.typeCode = typeCode;
    }
 
    public String getTypeCode() {
        return typeCode;
    }
 
    public int getCount() {
        return count;
    }
 
    public void reset() {
        this.count = 0;
    }
 
    public void inc() {
        inc(1);
    }
 
    public void inc(final int count) {
        this.count += count;
    }
}

angularCNG/backoffice/src/example/cng/angular/session/UserNameSessionDecorator.java

package example.cng.angular.session;
 
import com.hybris.cockpitng.util.js.JsWidgetSessionDTO;
import com.hybris.cockpitng.util.js.JsWidgetSessionInfoDecorator;
import de.hybris.platform.servicelayer.user.UserService;
import org.springframework.beans.factory.annotation.Required;
 
public class UserNameSessionDecorator implements JsWidgetSessionInfoDecorator {
 
    private UserService userService;
 
    @Override
    public JsWidgetSessionDTO decorate(final JsWidgetSessionDTO dto) {
        dto.addCustomAttribute("name", getUserService().getCurrentUser().getDisplayName());
        return dto;
    }
 
    public UserService getUserService() {
        return userService;
    }
 
    @Required
    public void setUserService(final UserService userService) {
        this.userService = userService;
    }
}