I use at frontend AngularJS 1.4 and at Backend Java and I have a lot of options which can be selected in frontend, e.g. the country:
GERMANY
FRANCE
USA
RUSSIA
Enums are written in upper case and I will customize this in frontend (e.g. FRANCE will become to France).
My question now would be if there is a directive or a any other support doing this in frontend.
In view:
<select ng-model="selectedCountry" ng-options="country as country.name for country in countries | filter:filterUpperCamelCase"></select>
In controller:
$scope.countries= [
{name:"SPAIN"},
{name:"GERMANY"}
];
$scope.filterUpperCamelCase = function(element){
element.name = element.name.toLowerCase();
element.name = element.name.charAt(0).toUpperCase() + element.name.slice(1);
return element;
};
Check out this link
http://hello-angularjs.appspot.com/angularjs-create-custom-filter
It has a custom filter written which can help you out.
Here's code from link given above.
<!DOCTYPE html>
<html ng-app="HelloApp">
<head>
<title></title>
</head>
<body ng-controller="HelloCtrl">
<form>
<input type="text" ng-model="name"/>
</form>
<div>{\{name|titlecase}}</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
// Code defining custom module consisting of a filter
// The module needs to be included as dependency for using the filter, titlecase
//
angular.module('CustomFilterModule', [])
.filter( 'titlecase', function() {
return function( input ) {
return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
});
// Angular App on this page
// Included CustomFilterModule as dependency
//
angular.module('HelloApp', [ 'CustomFilterModule'])
.controller('HelloCtrl', ['$scope', function($scope){
$scope.name = '';
}])
</script>
</body>
</html>
Related
I wish to make an online java editor like ideone.com
I wish to use https://ace.c9.io/#nav=about&api=anchor to make my tool.
I have used codeEditor.session.setMode("ace/mode/java"); but stil my tool does not compile java language.
Till now my code is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="lib/css/editor-styles.css">
<title>Online Test</title>
</head>
<body>
<div class="editor">
<div class="editor__wrapper">
<div class="editor__body">
<div id="editorCode" class="editor__code"></div>
</div>
<div class="editor__footer">
<div class="editor__footer--left">
<button class="editor__btn editor__run">Run ></button>
<button class="editor__btn editor__reset">Reset ></button>
</div>
<div class="editor__footer--right">
<div class="editor__console">
<ul class="editor__console-logs"></ul>
</div>
</div>
</div>
</div>
</div>
<!-- Required Ace Libraries -->
<script src="lib/js/ace-editor/src-min/ace.js"></script>
<script src="lib/js/ace-editor/src-min/mode-javascript.js"></script>
<script src="lib/js/ace-editor/src-min/ext-language_tools.js"></script>
<!-- Custom Scripts -->
<script src="lib/js/editor.js"></script>
<script src="lib/js/editor-console.js"></script>
</body>
</html>
// Retrieve Elements
const consoleLogList = document.querySelector('.editor__console-logs');
const executeCodeBtn = document.querySelector('.editor__run');
const resetCodeBtn = document.querySelector('.editor__reset');
Building a Code Editor for the Web - Configuring Ace Editor
Building a Code Editor for the Web - Configuring Ace Editor
JS FILE
// Setup Ace
let codeEditor = ace.edit("editorCode");
let defaultCode = 'console.log("Editor")';
let consoleMessages = [];
let editorLib = {
clearConsoleScreen() {
consoleMessages.length = 0;
// Remove all elements in the log list
while (consoleLogList.firstChild) {
consoleLogList.removeChild(consoleLogList.firstChild);
}
},
printToConsole() {
consoleMessages.forEach(log => {
const newLogItem = document.createElement('li');
const newLogText = document.createElement('pre');
newLogText.className = log.class;
newLogText.textContent = `> ${log.message}`;
newLogItem.appendChild(newLogText);
consoleLogList.appendChild(newLogItem);
})
},
init() {
// Configure Ace
// Theme
codeEditor.setTheme("ace/theme/monokai");
// Set language
codeEditor.session.setMode("ace/mode/java");
// Set Options
codeEditor.setOptions({
fontFamily: 'Inconsolata',
fontSize: '12pt',
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
});
// Set Default Code
codeEditor.setValue(defaultCode);
}
}
// Events
executeCodeBtn.addEventListener('click', () => {
// Clear console messages
editorLib.clearConsoleScreen();
// Get input from the code editor
const userCode = codeEditor.getValue();
// Run the user code
try {
new Function(userCode)();
} catch (err) {
console.error(err);
}
// Print to the console
editorLib.printToConsole();
});
resetCodeBtn.addEventListener('click', () => {
// Clear ace editor
codeEditor.setValue(defaultCode);
// Clear console messages
editorLib.clearConsoleScreen();
})
editorLib.init();
How to add compile feature to it?
Hypothetically ... you get your editor to send the source code to a server that has a Java compiler installed and you run it.
If your app's server side is implemented in Java, you could make use of Java's runtime compilation APIs. See How do I programmatically compile and instantiate a Java class?. (Skip over the part about loading and running the compiled code ... unless you want to do that too.)
Ace is an editor, not a compiler.
You can't use it to compile code.
Ideone use Sphere Engine Compilers to compile...
Refer this documentation : link
I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>
Lets say I want to pass a List of strings to my template and create a ul by iterating over it. And I don't want to use ng-init.
Action :
public static Result login(){
List<String>Names = Arrays.asList("Tom","Dick","Harry");
return ok(login.render(Names));
}
login.scala.html:
#(names: List[String])
<!DOCTYPE html>
<html ng-app="app">
<body>
<div ng-controller="appCtrl">
<ul>
<li ng-repeat="name in names">{{name}}</li>
</ul>
</div>
</body>
<script>
app = angular.module("app", []);
app.controller('appCtrl', function($scope){
$scope.names = #Html(names);
//This does not work
// Error : type mismatch; found : java.util.List[String] required: String
});
</script>
</html>
As said, you could use Scala formating before passing to #Html to display it without escaping.
<!-- language: scala -->
#Html(names.mkString("[",",","]"))
// Formats list by starting with '[', ending with ']', with ',' as separator
// aka JS format for array
#Html(names.mkString("""["""", """","""", """"]"""))
// wraps array values with ""
N.B. If your string values contain " character, extra formatting would be required.
Can we initialize JavaScript variables with java in jsp page?
like,
<script type="text/javascript">
var refreshId = setInterval(function() {
var nv=<% out.print(num_voted); %>;
var tv=<%out.print(totalvoted); %>;
var m=<% out.print(month);%>;
var y=<% out.print(year);%>;
alert("refreshed");
$('#alertmessagebox').text("Total members voted "+nv+" out of "+tv+" for "+m+" " +y);
}, 9000);
$.ajaxSetup({ cache: false });
</script>
Code is not working as expected. :(
Is there way to do this? Why it is not possible by this way? shall we need to create header to do this?
Here is an example of setting Javascript variables in a JSP.
<head>
<%
String numVotedStr = request.getParameter("numvoted");
int numVoted = 0;
if (numVotedStr != null) {
numVoted = Integer.parseInt(numVotedStr);
}
%>
<script type="text/javascript">
function setInterval() {
alert("hello " + <%= numVoted %>);
}
</script>
</head>
<body>
<form>
<input type="button" onclick="setInterval()" value="Press Me"/>
</form>
</body>
</html>
To test, use the appropriate version of this URL:
http://localhost:8080/sandbox/example.jsp?numvoted=99
This will popup an alert box with the integral value of "numvoted" on the HTTP request, by producing an HTML page where the value is initialized in Javascript. (The code should have at least a try-catch for the parseInt() call, but this will serve as simple example.)
I have a map that you can click on locations to get information for that area and I would like to show that information in a Iframe on the same page when clicked
My page has this for the link now
`<AREA SHAPE="CIRCLE" COORDS="555,142,6" HREF="http://www.Page.com" TITLE="" />`
Any suggestions
The beauty of AJAX is that you don't really need an IFRAME to do this.
You've got a server that will return to you information about a certain area. Each of the AREA tags simply needs an onclick attribute that calls a JavaScript function to retrieve that information and display it in a location you set aside on your page.
Here is a sample HTML page that will retrieve information from the server using AJAX
<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
var infoBox = document.getElementById("infoBox");
if (infoBox == null) return true;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status != 200) alert(xhr.status);
infoBox.innerHTML = xhr.responseText;
};
xhr.open("GET", "info.php?id=" + id, true);
xhr.send(null);
return false;
}
</script>
<style type="text/css">
#infoBox {
border:1px solid #777;
height: 400px;
width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
Area One
Area Two
Area Three
</p>
<p>Here is where the information will go.</p>
<div id="infoBox"> </div>
</body>
</html>
And here is the info.php that returns the information back to the HTML page:
<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>
Hope this helps!