WebSocket + AngularJS client - angularjs

Goal: Develop a WebSocket + AngularJS client
My goal is to create a WebSocket client using AngularJS, the program is expected to send a message to the java server which replies with the same message and the date.
The server side works fine (it is shown below, (implemented using java)
I have tested it with a regular javascript web socket program)
My issue:
The client-side with AngularJS doesn't work.
Maybe I used the wrong library for this project.
Here is the WebSocket library I use for AngularJS :
https://github.com/AngularClass/angular-websocket
Client side - this doesn't work - what am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="lib/angular.min.js"></script>
<script type="text/javascript" src="lib/angular-websocket.js"></script>
<script type="text/javascript">
var app = angular.module('websocket',[]);
app.service('WebSocketWrapper', ['$log', '$websocket', '$rootScope', function($log, $websocket, $rootScope){
this.ws = null; // Attach ws to service object
this.state = 'initializing';
this.message = 'websocket initializing';
var self = this;
this.init = function(){
if(!this.ws){
this.ws = $websocket('ws://127.0.0.1:8080/WebSocketHome/echo', null, {reconnectIfNorNormalClose: true});
this.ws.onClose(function(){
console.info('close');
$rootScope.$apply(function(){
self.state = 'disconnected';
self.message = 'Websocket disconnected';
});
});
this.ws.onOpen(function(){
console.info('connected');
$rootScope.$apply(function(){
self.state = 'connected';
self.message = 'websocket connected';
});
});
this.ws.onMessage(function(message){
console.log("RECEIVED : " + message);
});
}
};
}]);
app.controller('WebSocketStateCtrl', ['$scope', 'WebSocketWrapper', function($scope, WebSocketWrapper){
$scope.websocket = WebSocketWrapper;
$scope.websocket.init();
$scope.sendMsg = function sendMsg() {
var message = textId.value;
display("Message send : " + message);
websocket.send(message);
//ws.send(message);
}
$scope.display = function display(message) {
var ligne = document.createElement("p");
ligne.innerHTML = message;
messageDiv.appendChild(ligne);
}
}]);
</script>
</head>
<body>
<div id="messageDivId"></div>
ClickMe
<!-- this div displays the status of the websocket connection -->
<div data-ng-controller="WebSocketStateCtrl">
<span data-ng-bind="websocket.message"></span>
<span class="circle" data-ng-class="{initializing: websocket.state === 'initializing',
connected : websocket.state === 'connected',
disconnected: websocket.state === 'disconnected',
reconnecting: websocket.state === 'reconnecting'}">
</span>
<div style="text-align: center;">
<form action="">
<input id="textId" name="message" value="" type="text">
<button ng-click="sendMsg()">SEND</button>
</form>
</div>
</div>
</body>
</html>
Server side - This works fine:
package org.example.websocket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class DeviceWebSocketServer {
#OnMessage
public String echo(String message){
System.out.println("Message reçu : " + message);
return ThreadSafeFormatter.getDateFormatter().format(new Date()) + " " + message;
}
}
class ThreadSafeFormatter {
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
#Override
protected SimpleDateFormat initialValue(){
return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
}
};
public static DateFormat getDateFormatter(){
return formatter.get();
}
}
HTML Page Code
The html page in regular javascript which shows the server side works fine :
<!DOCTYPE html>
<html>
<head>
<title>Test WebSockets</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script language="javascript" type="text/javascript">
var wsUri = getRootUri() + "/WebSocketHome/echo";
function getRootUri() {
return "ws://"
+ (document.location.hostname == "" ? "localhost" : document.location.hostname)
+ ":"
+ (document.location.port == "" ? "8080" : document.location.port);
}
function init() {
messageDiv = document.getElementById("messageDivId");
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
afficher("CONNECTE");
}
function onMessage(evt) {
afficher("RECU : " + evt.data);
}
function onError(evt) {
afficher('<span style="color: red;">ERREUR:</span> ' + evt.data);
}
function envoyer() {
var message = textId.value;
afficher("ENVOYE : " + message);
websocket.send(message);
}
function afficher(message) {
var ligne = document.createElement("p");
ligne.innerHTML = message;
messageDiv.appendChild(ligne);
}
window.addEventListener("load", init, false);
</script>
</head>
<body>
<h2 style="text-align: center;">Client WebSocket Echo</h2>
<div style="text-align: center;">
<form action="">
<input id="textId" name="message" value="" type="text">
<input onclick="envoyer()" value="Envoyer" type="button">
</form>
</div>
<div id="messageDivId"></div>
ClickMe
</body>
</html>

Related

Not able to run angularjs code on the computer

Not able to run the angular js code in the following program on my pc. It is working in the plunker editor online.Please let me know if i need to download any thing before i will be able to run the code . Thanks in advance
Html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The angularjs app!</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
<script src="C:\Users\komar\Desktop\script.js"></script>
</head>
<body>
<div ng-app="MyModule" ng-controller="MyController as ctrl">
<b>Invoice:</b><br>
<div>
Quantity:<input type = "number" min = 0 ng-model = "ctrl.quantity" required><br>
Costs:<input type = "number" min=0 ng-model="ctrl.costs" required>
<select ng-model="ctrl.selCur">
<option ng-repeat = "c in ctrl.currencies">{{c}}</option>
</span><br>
<b>Total:</b><span ng-repeat= "c in ctrl.currencies">
{{ctrl.convert(c) | currency:c}}
</span><br>
<button class ="btn" ng-click="ctrl.createAlert()">Pay</button>
</div>
</div>
</body>
</html>
Javascript code:
var app = angular.module('MyModule');
app.controller('MyController',[MyService,function MyController(MyService){
this.quantity = 1;
this.costs =2;
this.selCur = 'EUR';
this.currencies = MyService.currencies;
var convert = function(baseCur){
return MyService.currentCurrencies(this.quantity*this.costs,this.selCur,baseCur);
}
this.createAlert = function createAlert(){
window.alert('Thanks!');
};
}]);
app.factory('MyService',function(){
var currencies= ['USD','EUR','CNY'];
var values = {
USD: 1,
EUR: 0.88,
CNY: 6.72
};
var currentCurrencies = function(amount,selCur,baseCur){
return amount*values(selCur)/values(baseCur);
}
return {
currentCurrencies: currentCurrencies,
currencies: currencies
};
});
I am not able to run this code . please help me fix the issues and help run the code
Even this code is not working
HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-guide-concepts-21-production</title>
<script src="//code.angularjs.org/1.7.7/angular.min.js"></script>
<script src="finance2.js"></script>
<script src="invoice2.js"></script>
</head>
<body >
<div ng-app="invoice2" ng-controller="InvoiceController as invoice">
<b>Invoice:</b>
<div>
Quantity: <input type="number" min="0" ng-model="invoice.qty" required >
</div>
<div>
Costs: <input type="number" min="0" ng-model="invoice.cost" required >
<select ng-model="invoice.inCurr">
<option ng-repeat="c in invoice.currencies">{{c}}</option>
</select>
</div>
<div>
<b>Total:</b>
<span ng-repeat="c in invoice.currencies">
{{invoice.total(c) | currency:c}}
</span><br>
<button class="btn" ng-click="invoice.pay()">Pay</button>
</div>
</div>
</body>
</html>
script files
(function(angular) {
'use strict';
angular.module('finance2', [])
.factory('currencyConverter', function() {
var currencies = ['USD', 'EUR', 'CNY'];
var usdToForeignRates = {
USD: 1,
EUR: 0.74,
CNY: 6.09
};
var convert = function(amount, inCurr, outCurr) {
return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
};
return {
currencies: currencies,
convert: convert
};
});
})(window.angular);
(function(angular) {
'use strict';
angular.module('invoice2', ['finance2'])
.controller('InvoiceController', ['currencyConverter', function InvoiceController(currencyConverter) {
this.qty = 1;
this.cost = 2;
this.inCurr = 'EUR';
this.currencies = currencyConverter.currencies;
this.total = function total(outCurr) {
return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
};
this.pay = function pay() {
window.alert('Thanks!');
};
}]);
})(window.angular);
You have to change the
var app = angular.module('MyModule');
to
var app = angular.module('MyModule', []);
Check the []
Also
app.controller('MyController',[MyService,function MyController(MyService){
To
app.controller('MyController',["MyService",function MyController(MyService){
Check the " in MyService
Few more fixes
There are some more fixes,
You have to close the tag.
return amount*values[selCur]/values[baseCur]; <- Here changed ( to [
var convert = has to be changed to this.convert =
Please use <script></script> instead <script src="C:\Users\komar\Desktop\script.js"></script>, and copy your JavaScript between the script tag.
Find the updated code below
var app = angular.module('MyModule', []);
app.controller('MyController', ["MyService", function MyController(MyService) {
this.quantity = 1;
this.costs = 2;
this.selCur = 'EUR';
this.currencies = MyService.currencies;
var convert = function(baseCur) {
return MyService.currentCurrencies(this.quantity*this.costs, this.selCur, baseCur);
}
this.createAlert = function createAlert() {
window.alert('Thanks!');
};
}]);
app.factory('MyService', function() {
var currencies = ['USD', 'EUR', 'CNY'];
var values = {
USD: 1,
EUR: 0.88,
CNY: 6.72
};
var currentCurrencies = function(amount, selCur, baseCur) {
return amount*values(selCur)/values(baseCur);
}
return {
currentCurrencies: currentCurrencies,
currencies: currencies
};
});
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The angularjs app!</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="MyModule" ng-controller="MyController as ctrl">
<b>Invoice:</b><br>
<div>
Quantity:<input type = "number" min = 0 ng-model = "ctrl.quantity" required><br>
Costs:<input type = "number" min=0 ng-model="ctrl.costs" required>
<select ng-model="ctrl.selCur">
<option ng-repeat = "c in ctrl.currencies">{{c}}</option>
</span><br>
<b>Total:</b><span ng-repeat= "c in ctrl.currencies">
{{ctrl.convert(c) | currency:c}}
</span><br>
<button class ="btn" ng-click="ctrl.createAlert()">Pay</button>
</div>
</div>
</body>
</html>
Your HTML code is correct you just need to change the script.js file code with following code.
var app = angular.module('MyModule', []);
app.controller('MyController',['$scope','MyService',function MyController(MyService, $scope){
this.quantity = 1;
this.costs =2;
this.selCur = 'EUR';
this.currencies = MyService.currencies;
var convert = function(baseCur){
return MyService.currentCurrencies(this.quantity*this.costs,this.selCur,baseCur);
}
this.createAlert = function createAlert(){
window.alert('Thanks!');
};
}]);
app.factory('MyService',function(){
var currencies= ['USD','EUR','CNY'];
var values = {
USD: 1,
EUR: 0.88,
CNY: 6.72
};
var currentCurrencies = function(amount,selCur,baseCur){
return amount*values(selCur)/values(baseCur);
}
return {
currentCurrencies: currentCurrencies,
currencies: currencies
};
});

File drag and drop functionality in Angular js/MVC not working

I am trying to implement a simple file drag and drop functionality in Angular js/MVC.
I created a directive for the drag and drop.
(function (angular, undefined) {
'use strict';
angular.module('fileupload', [])
.directive("myDirective", function ($parse) {
return {
restrict: 'A',
link: fileDropzoneLink
};
function fileDropzoneLink(scope, element, attrs) {
element.bind('dragover', processDragOverOrEnter);
element.bind('dragenter', processDragOverOrEnter);
element.bind('dragend', endDragOver);
element.bind('dragleave', endDragOver);
element.bind('drop', dropHandler);
var onImageDrop = $parse(attrs.onImageDrop);
//When a file is dropped
var loadFile = function (files) {
scope.uploadedFiles = files;
scope.$apply(onImageDrop(scope));
};
function dropHandler(angularEvent) {
var event = angularEvent.originalEvent || angularEvent;
var files = event.dataTransfer.files;
event.preventDefault();
loadFile(files)
}
function processDragOverOrEnter(angularEvent) {
var event = angularEvent.originalEvent || angularEvent;
if (event) {
event.preventDefault();
}
event.dataTransfer.effectAllowed = 'copy';
element.addClass('dragging');
return false;
}
function endDragOver() {
element.removeClass('dragging');
}
}
});
}(angular));
This is the template
<div class="dropzone" data-my-Directive on-image-drop="$ctrl.fileDropped()">
Drag and drop pdf files here
</div>
This is my component code
(function (angular, undefined) {
'use strict';
angular.module('test', [])
.component('contactUs', contactUs());
function contactUs() {
ContactUs.$inject = ['$scope', '$http'];
function ContactUs($scope, $http) {
var ctrl = this;
ctrl.files = [];
ctrl.services = {
$scope: $scope,
$http: $http,
};
}
//file dropped
ContactUs.prototype.fileDropped = function () {
var ctrl = this;
var files = ctrl.services.$scope.uploadedFiles;
angular.forEach(files, function (file, key) {
ctrl.files.push(file);
});
}
return {
controller: ContactUs,
templateUrl: 'partials/home/contactus/'
};
}
}(angular));
Sometimes the drag and drop works absolutely fine without any issue. But some times I get the below issue and the drag and drop does not work and I get the black invalid cursor.
This issue is random and i do not see any errors in the console.
And I also tried other third party components like angular-file-upload
https://github.com/nervgh/angular-file-upload and I am seeing the exact same issue with that component also.
EDIT :
Answer updated for pdf preview. The code is available in the same plunker.
References : Excellent solution by #Michael at https://stackoverflow.com/a/21732039/6347317
In the example above, the response from the http POST is used in "new Blob([response]". In angular-file-upload library, the "response" would be "fileItem._file" property in "uploader.onAfterAddingFile" function. You can console log to check the data these have , so as to understand it better.
Also please note that if PDf viewer is not enabled in chrome, it has to be enabled using this: https://support.google.com/chrome/answer/6213030?hl=en
END EDIT
Since you mentioned that you tried with angular-file-upload library, i have created a plunker with it:
http://plnkr.co/edit/jeYg5fIRaC9wuEYSNOux?p=info
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/2.5.0/angular-file-upload.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="col-sm-4">
<h3>Select files</h3>
<div ng-show="uploader.isHTML5">
<!-- 3. nv-file-over uploader="link" over-class="className" -->
<div class="well my-drop-zone" style="width:300px" nv-file-drop nv-file-over="" uploader="uploader"
filters="syncFilter">
<label>
Click here or Drag and Drop file
<input type="file" style="visibility:hidden;" nv-file-select nv-file-over="" uploader="uploader"
filters="syncFilter" multiple/>
</label>
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.queue[0].progress + '%' }"></div>
</div>
<div>{{uploader.queue[0].file.name}}</div>
<div ng-show="showAlert" class="alert alert-warning alert-dismissable">
×
<strong>Clear the existing file before uploading again!!</strong>
</div>
</div>
</div>
</div>
</body>
</html>
JS:
var app = angular.module('plunker', ['angularFileUpload']);
app.controller('MainCtrl', function($scope,FileUploader) {
var uploader = $scope.uploader = new FileUploader();
// FILTERS
// a sync filter
uploader.filters.push({
name: 'syncFilter',
fn: function(item /*{File|FileLikeObject}*/, options) {
console.log('syncFilter' + this.queue.length);
return this.queue.length < 1;
}
});
// an async filter
uploader.filters.push({
name: 'asyncFilter',
fn: function(item /*{File|FileLikeObject}*/, options, deferred) {
console.log('asyncFilter');
setTimeout(deferred.resolve, 1e3);
}
});
uploader.allowNewFiles = true;
uploader.filters.push({
name:'csvfilter',
fn: function() {
return this.allowNewFiles;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
$scope.showAlert=true;
};
uploader.onAfterAddingFile = function(fileItem) {
};
});
It is pretty straight forward and i dont get the error you mentioned. We are actually using this library in one of our Projects. I have also added a filter to restrict upload to only 1 file.
Please check this and let me know how it goes or if you have any doubts in the code.

AngularJS code is not running and getting no error message when inspected

When I inspect it, there are no error and it's returning nothing so, apparently not running :
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles/bootstrap.min.css">
<style>
.message {
font-size: 1.3em;
font-weight: bold;
}
</style>
<script src="angular.min.js"></script>
</head>
<body ng-app='LunchChecker'>
<div class="container" ng-controller='MyLunchCheckController'>
<h1>Lunch Checker</h1>
<div class="form-group">
<input id="lunch-menu" type="text" placeholder="list comma separated dishes
you usually have for lunch" class="form-control" ng-model='MenuInput'>
</div>
<div class="form-group">
<button class="btn btn-default" ng-click="checkInput()">
Check If Too Much</button>
</div>
<div class="form-group message" {{checkInput()}}>
<!-- Your message can go here. -->
</div>
</div>
<script src="app.js"></script>
</body>
</html>
Below is the app.js script for the above view the purpose of the code is to return either msg1 if the input is less than 3 menu or msg2 if the input is more than 3 :
(function() {
'use strict';
angular.module('LunchChecker', [])
.controller('MyLunchCheckController', MyLunchCheckController);
MyLunchCheckController.$inject = ['$scope'];
function MyLunchCheckController($scope) {
$scope.MenuInput = [].slice;
$scope.values = new Array($scope.MenuInput.length);
$scope.msg1 = "Enjoy!";
$scope.msg2 = "Too much!";
//fucntion for the button to check the user input menu-list
$scope.checkInput = function() {
for (var i = 0; i < $scope.values; i++) {
if ($scope.values <= 3) {
return $scope.msg1;
} else {
return $scope.msg2;
}
}
};
}
})();
When I try to reflect your code, I am getting function slice() { [native code] } inside the text box. As you have initialised the value of MenuInput as [].slice.
So to improve and compare the code
'use strict';
angular.module('LunchChecker', [])
.controller('MyLunchCheckController', ['$scope', function($scope) {
$scope.msg1 = "Enjoy!";
$scope.msg2 = "Too much!";
$scope.checkInput = function() {
if($scope.MenuInput.split(",").length <= 3) {
$scope.values = $scope.msg1;
} else{
$scope.values = $scope.msg2;
}
};
}]);
It will print the message in the console according to the length you compare. For displaying the message you can write like:
<div class="form-group message" {{checkInput()}}>
to
<div class="form-group message"> {{values}}</div>

display the post data in the angular js jsp page

i have a form designed with angular js, upon submit it post the data to the spring controller, which intern processes the data to be displayed in the new jsp page.
part 1: form submit through angular js to the spring controller (Completed)
part 2: Spring controller to process the post data and return the json string object (completed)
part 3: The data received in the success part of the spring controller and displaying the data in the new jsp page (yet to completed, need help).
Problem here is that i can post the json data , but could not able to display the json date in the jsp page (AuditDisplayResultPage.jsp), basically i cannot accomplish the part3.
part 1 source code
AuditDisplayPage.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/LDODashBoard/js/scripts.js" language="JavaScript" type="text/javascript"></script>
<script src="/LDODashBoard/js/AuditDisplayPage.js" language="JavaScript" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
<link rel="stylesheet" type="text/css" href="/LDODashBoard/css/mystyle.css" />
<link rel="stylesheet" type="text/css" href="/LDODashBoard/css/AuditDisplayPage.css" />
<body>
<div ng-app="myApp" ng-controller="myCtrl" style="color:white" div align="left">
<br/><br/>
<form name = "audit" novalidate>
<label for="marketArraySel" >Market:</label>
<select id="marketArraySel" ng-model="marketArraySel" ng-options="market as getMarketFullName(market) for market in marketArray | orderBy:'name' track by market.id" ng-change="updateChanges()" ng-selected="selectedExpression()">
<option value="">[NO SELECTION]</option>
</select>
<label for="accountText" >Account:</label>
<input type="text" id="accountText" ng-model="accountName" ng-change="onAccountTextChange()"></input>
<br/>
<label for="marketNameType" >Type the Market:</label>
<input type="text" id="marketNameType" ng-model="marketNameType" ng-change="selectmarketByName(marketNameType)" />
<br/><br/>
<label for="textareavalue" ng-show="marketArraySel.id && accountName">Selected Details:</label>
<textarea id="textareavalue" ng-model="textareavalue" style="color:blue" disabled ng-show="marketArraySel.id && accountName">{{textareavalue}}</textarea>
<br />
<!--
<span size=10><STRONG> Selected Market: {{marketArraySel.name}} </STRONG> </span>
<span id="tab"></span>
<span id="tab"></span>
<span id="tab"></span>
<span id="tab"><STRONG> Selected Account: {{accountName}} </STRONG></span>
-->
<br/> <br/>
<input type="reset" ng-click="reset()" value="RESET"></input>
<input type="button" ng-click="submitfunction()" value="SUBMIT" ng-disabled="!marketArraySel.id && !accountName"></input>
</form>
<br><br>
<span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span>
<c:url value="/L1OutputDisplayPage?gcmmLink2=true" var="messageUrl2" />
Click Here
to Close
</div>
</body>
</html>
AuditDisplayPage.js
$scope.submitfunction = function() {
var dataObj = {
name : getById($scope.marketArray,$scope.marketArraySel.id),
account : $scope.accountName,
database : getDatabaseById($scope.marketArray,$scope.marketArraySel.id)
};
$http({
'url' : '/LDODashBoard/AuditDisplayPost',
'method' : 'POST',
'headers': {'Content-Type' : 'application/json'},
'data' : dataObj
})
.success(function(data, status, headers,config,ele) {
window.alert('Success4');
$scope.message = data;
//covert the json object to string
//var message1 = JSON.stringify($scope.message);
window.alert('message1:' + message1);
//window.location("/LDODashBoard/AuditDisplayPostResponse?argument1=" + "hello");
window.location("/LDODashBoard/AuditDisplayPostResponse?argument1=" + message);
/*
Message value
{"cvAuditClassList":[{"db_seq":13084,"operator":"cricha19","action":"I","cv_table":12,"id":3006538,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":31244,"operator":"cricha19","action":"I","cv_table":12,"id":3014027,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":40739,"operator":"gdennis2","action":"U","cv_table":5,"id":3014027,"comments":"Clair:AAKASH AGARWAL;"},{"db_seq":56740,"operator":"mzak1","action":"I","cv_table":12,"id":3043260,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":56748,"operator":"mzak1","action":"I","cv_table":12,"id":3043264,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":52647,"operator":"bkamins11","action":"I","cv_table":12,"id":3041524,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":76771,"operator":"rmarczak","action":"I","cv_table":12,"id":3053777,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":76772,"operator":"rmarczak","action":"I","cv_table":13,"id":3053777,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":74719,"operator":"iteppel","action":"I","cv_table":13,"id":3043264,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":74749,"operator":"iteppel","action":"I","cv_table":13,"id":3043260,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":79437,"operator":"aimierow","action":"I","cv_table":12,"id":3054314,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":79438,"operator":"aimierow","action":"I","cv_table":13,"id":3054314,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":113297,"operator":"iteppel","action":"I","cv_table":12,"id":3106380,"comments":"Acc:B825M;Firm:L;Off:;Sungard:;"},{"db_seq":113298,"operator":"iteppel","action":"I","cv_table":13,"id":3106380,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":113299,"operator":"iteppel","action":"U","cv_table":5,"id":3106380,"comments":"Clair:cs;"},{"db_seq":113300,"operator":"iteppel","action":"I","cv_table":9,"id":3006538,"comments":"Name:%GI-YP2MD%;Broker:%;Ctr:%;CbType:0;AccOptFut:47;CtrType:;"},{"db_seq":113301,"operator":"iteppel","action":"D","cv_table":9,"id":3006538},{"db_seq":113302,"operator":"iteppel","action":"I","cv_table":9,"id":3006538,"comments":"Name:%GI-YP2MD%;Broker:CSBLO;Ctr:%;CbType:0;AccOptFut:47;CtrType:;"},{"db_seq":113303,"operator":"iteppel","action":"D","cv_table":9,"id":3006538},{"db_seq":113304,"operator":"iteppel","action":"I","cv_table":9,"id":3006538,"comments":"Name:%GI-YP2MD%;Broker:CSILO;Ctr:%;CbType:0;AccOptFut:47;CtrType:;"},{"db_seq":109823,"operator":"mskiba","action":"I","cv_table":12,"id":3082104,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":109824,"operator":"mskiba","action":"I","cv_table":13,"id":3082104,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125379,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118253,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125380,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118253,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125382,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118254,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125383,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118254,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125385,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118255,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125386,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118255,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125388,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118256,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125389,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118256,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"}]}
*/
})
.error(function(data, status, headers, config) {
window.alert('Error2');
$scope.message1 = data;
});
window.alert("alert4");
};
part 2 source code
DatabaseController.java
#RequestMapping(value = "/AuditDisplayPost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String auditDisplayPost(
#RequestBody AuditDisplayPostClass postClass, UriComponentsBuilder ucb) {
QueryExecutionResults execResults = null;
log.info("inisde AuditDisplayPost method");
log.info("auditdisplaypostclass name:" + postClass.getName());
log.info("auditdisplaypostclass account:" + postClass.getAccount());
log.info("auditdisplaypostclass database:" + postClass.getDatabase());
CVAuditDisplayResponse auditResponse = new CVAuditDisplayResponse();
CVAuditStaticUserParams cvstaticparams = new CVAuditStaticUserParams();
cvstaticparams.setNames(DBCheckoutBean.retrieveStringTokenQuery(postClass.getAccount()," "));
execResults = queryexecutorimplbean.executeQueryWrapperByQueryID(CommonConstants.CVAuditStaticUser,postClass.getDatabase(),cvstaticparams);
List <CVAuditStaticUserClass> listobject = execResults.getCvAuditStaticRowColRslt();
log.info("CVAuditStaticUser execResults list object size:" + listobject.size());
auditResponse.setCvAuditClassList(listobject);
log.info("Converting the auditresponse object to json string");
String json = new Gson().toJson(auditResponse);
log.info("printing the json:" + json);
return json;
}
part 3 source code ( NEED YOUR HELP)
DatabaseController.java
#RequestMapping(value = "/AuditDisplayPostResponse", method = RequestMethod.GET,consumes=MediaType.APPLICATION_JSON_VALUE)
public ModelAndView auditDisplayResponse(
#RequestParam(value = "argument1", required = false) String argument1){
log.info("inisde auditDisplayResponse method");
String json = "";
try {
//convert string to json
json = "[" + argument1 + "]";
log.info("argument1:" + argument1);
log.info("argument1 json:" + json);
}
catch(Exception e){
e.printStackTrace();
}
return (new ModelAndView("AuditDisplayResultPage","DisplayResponse",json));
//return (new ModelAndView("L1OutputDisplayPage","message",json));
}
umm..
log.info("inisde auditDisplayResponse method");
Map<String, String> model = new HashMap<String,String>();
try {
//convert string to json
json = "[" + argument1 + "]";
log.info("argument1:" + argument1);
log.info("argument1 json:" + json);
model.put("jsonData", json);
}
catch(Exception e){
e.printStackTrace();
}
return (new ModelAndView("AuditDisplayResultPage","DisplayResponse",model));
and client side
<html>
<body>
<h2>message : ${jsonData}</h2>
</body>
</html>

broadcasting model changes

I'm trying to set up a little POC to see whether or not angular would work for something I'm in the middle of.
I set up a REST server which I am able to CRUD with via angular. However, as the documentation and tutorials out there are so all over the place (read: SUPER inconsistent), I am not sure that the behavior I'm not seeing is the result of incorrect code or it's not something I can do like this.
I've gleaned from the docs that two-way binding is available, but it isn't clear how it works. NB I've read dozens of articles explaining how it works at a low level a'la https://stackoverflow.com/a/9693933/2044377 but haven't been able to answer my own question.
I have angular speaking to a REST service which modifies a sql db.
What I am wondering about and am trying to POC is if I have 2 browsers open and I change a value in the db, will it reflect in the other browser window?
As I said, I have it updating the db, but as of now it is not updating the other browser window.
app.js
angular.module('myApp', ['ngResource']);
var appMock = angular.module('appMock', ['myApp', 'ngMockE2E']);
appMock.run(function($httpBackend) {});
controllers.js
function MainCtrl($scope, $http, $resource) {
$scope.message = "";
$scope.fruits = [];
$scope.fruit = {};
$scope.view = 'partials/list.html';
var _URL_ = '/cirest/index.php/rest/fruit';
function _use_$resources_() { return false; }
function _fn_error(err) {
$scope.message = err;
}
$scope.listFruits = function() {
$scope.view = 'partials/list.html';
var fn_success = function(data) {
$scope.fruits = data;
};
$http.get(_URL_).success(fn_success).error(_fn_error);
}
function _fn_success_put_post(data) {
$scope.fruit = {};
$scope.listFruits();
}
function createFruit() {
$http.post(_URL_, $scope.fruit).success(function(data){
$scope.listFruits()
}).error(_fn_error);
}
function updateFruit() {
$http.post(_URL_, $scope.fruit).success(_fn_success_put_post).error(_fn_error);
}
function deleteFruit() {
$http.put(_URL_, $scope.fruit).success(_fn_success_put_post).error(_fn_error);
}
$scope.delete = function(id) {
if (!confirm("Are you sure you want do delete the fruit?")) return;
$http.delete("/cirest/index.php/rest/fruit?id=" + id).success(_fn_success_put_post).error(_fn_error);
}
$scope.newFruit = function() {
$scope.fruit = {};
$scope.fruitOperation = "New fruit";
$scope.buttonLabel = "Create";
$scope.view = "partials/form.html";
}
$scope.edit = function(id) {
$scope.fruitOperation = "Modify fruit";
$scope.buttonLabel = "Save";
$scope.message = "";
var fn_success = function(data) {
$scope.fruit = {};
$scope.fruit.id = id;
$scope.view = 'partials/form.html';
};
$http.get(_URL_ + '/' + id).success(fn_success).error(_fn_error);
}
$scope.save = function() {
if ($scope.fruit.id) {
updateFruit();
}
else {
createFruit();
}
}
$scope.cancel = function() {
$scope.message = "";
$scope.fruit = {};
$scope.fruits = [];
$scope.listFruits();
}
$scope.listFruits();
}
MainCtrl.$inject = ['$scope', '$http', '$resource'];
list.html
{{message}}
<hr/>
New Fruit
<ul ng-model="listFruit">
<li ng-repeat="fruit in fruits">
id [{{fruit.id}}] {{fruit.name}} is {{fruit.color}}
[X]
</li>
</ul>
index.html
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>FRUUUUUUUUUUUUUUUUUUUUUUUUUUUIT</title>
<link rel="stylesheet" href="css/bootstrap/css/bootstrap.css"/>
</head>
<body>
<div class="navbar">NAVBARRRRRRRRRRR</div>
<div class="container">
<div class="row">
<div ng-controller="MainCtrl">
<button ng-click="listFruits()">ListFruit()</button>
<button ng-click="cancel()">Cancel()</button>
<ng-include src="view"></ng-include>
</div>
</div>
</div>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
-->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
form.html
<h3>{{fruitOperation}}</h3>
<hr/>
<form name="fruitForm">
<input type="hidden" name="" ng-model="fruit.id" />
<p><label>name</label><input type="text" name="name" ng-model="fruit.name" value="dfgdfgdfg" required="true" /></p>
<p><label>color</label><input type="text" name="color" ng-model="fruit.color" value="fruit.color" required="true" /></p>
<hr/>
<input type="submit" ng-click="save()" value="{{buttonLabel}}" /> <button ng-click="cancel()">Cancel</button>
</form>
Thanks for any insight or pointers.
Two-way binding refers to changes occurring in your controller's scope showing up in your views and vice-versa. Angular does not have any implicit knowledge of your server-side data. In order for your changes to show up in another open browser window, for example, you will need to have a notification layer which pushes changes to the client via long polling, web sockets, etc.

Resources