Shared info of IoT & Cloud, Banking, Angular Wicket, Spring Reactive, AI, Flutter, E-comm, Java Telecomm and More.

Saturday, March 18, 2017

Cài đặt AngularJS 1.x với ví dụ giản đơn

Cài đặt AngularJS

Sau khi đã có những khái niệm căn bản về AngularJS, chúng ta sẽ tiến hành cài đặt để sử dụng AngularJS:
Step1: Tải tệp angular.min.js từ URL https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.min.js, rồi copy file vào thư mục js
Step2: Khai báo thư viện angularjs trong tệp html
<head><script src = "js/angular.min.js"></script> </head>

Step3: Khai báo thẻ gốc muốn áp dụng AngularJS với từ khóa ng-app. Thẻ với từ khóa này chỉ ra sự khởi đầu ứng dụng AngularJS.
<div ng-app>
</div>
Step4: Sử dụng các thẻ ng-model, ng-bind và các thẻ khác bên trong thẻ gốc ng-app để xây dựng các trang web với AngularJS
ví dụ hoàn chỉnh như sau:
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-guide-concepts-1-production</title>
  <script src="js/angular.min.js"></script>  
</head>
<body >
  <div ng-app ng-init="qty=1;cost=2">
  <b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" ng-model="qty">
  </div>
  <div>
    Costs: <input type="number" min="0" ng-model="cost">
  </div>
  <div>
    <b>Total:</b> {{qty * cost | currency}}
  </div>
</div>
</body>
</html>

Kiến trúc AngularJS 1.x

AngularJS là gì?

AngularJS là một web application framework mã nguồn mở dựa trên JavaScript để tạo ra các ứng dụng RICH Internet Application(RIA) hay ứng dụng sử dụng mô hình MVVM (Model-View-ViewModel).
có thể coi AngularJS tương tự như jQuery nhưng có nhiều tính năng hỗ trợ hơn cung cấp RESTful API, Two-Way data binding,..
AngularJS là một framework để có thể tạo được những ứng dụng web quy mô lớn và performance cao mà vẫn giữ duy trì được tính năng dễ dàng trong việc bảo trì.
Download tại https://angularjs.org/

Comparsion: Struts 2 vs Spring 3 MVC

Apache Struts 2 and Spring MVC are two of the most popular Java web frameworks today. I’ve used both APIs extensively and wanted to share a quick comparison.
In Struts, the object that handles a request and routes it for processing is called an Action. In Spring MVC, that object is referred to as a Controller. Actions and Controllers are pretty much the same thing – they take input, process it, and return some sort of response.
The one major design difference is that by default, Struts 2 Actions are newly instantiated every time a request is made, whereas in Spring MVC the default behavior is to act as a Singleton. Spring MVC Controllers are created once and held in memory/shared across all requests. Note, you can change this behavior (scope) to request or session but we’ll talk about that later. This is a major difference to keep in mind when designing applications that need to be thread-safe, database oriented, or other share-able transactions.

Saturday, February 25, 2017

Web Apps in WebView

To deliver a web application or some web pages as a part of an android client application, you can do it using WebView.
The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout. It does not include web browser, navigation controls or an address bar,.. just web page content.
WebView can be used to display static document that's hosted online.
WebView can also be used to build dynamic data for users.

How to get started with WebView ? How to do some additional things, such as handle page navigation and bind JavaScript from your web page to client-side code in your Android application.

Thursday, February 23, 2017

JavaScript căn bản - part 2


1. JavaScript Array splice() Method


Definition and Usage
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Note: This method changes the original array.

Syntax
array.splice(index, howmany, item1, ....., itemX)

Parameter Values

ParameterDescription
indexRequired. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
howmanyOptional. The number of items to be removed. If set to 0, no items will be removed
item1, ..., itemXOptional. The new item(s) to be added to the array
Return Value: A new Array, containing the removed items (if any)

Example

At position 2, add the new items, and remove 1 item:
var fruits = ["Banana""Orange""Apple""Mango"];
fruits.splice(21"Lemon""Kiwi");
=> result = Banana,Orange,Lemon,Kiwi,Mango

Example

At position 2, remove 2 items:
var fruits = ["Banana""Orange""Apple""Mango""Kiwi"];
fruits.splice(22);

Example

At position 2, remove 0 items and add 2 items:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "abc" , "Kiwi");
=> result = [Banana,Orange,abc,Kiwi,Apple,Mango]

2. valueOf() Method

<script>
function myFunction() {
    var str = "Hello World!";
    var res = str.valueOf();
    document.getElementById("demo").innerHTML = res;
}
</script>

3. Set and Map

Set:
mySet[Symbol.iterator]

Return value

The Set iterator function, which is the values() function by default.

Example:
vm.fileSetUpload = new Set();
var rmID = $('#btnRemoveSetupFileSrv').val();
vm.fileSetUpload.add(rmID.valueOf());
const iterator1 = vm.fileSetUpload[Symbol.iterator]();
vm.arrRmAttachFile = [];
for (var v of vm.fileSetUpload) {
    vm.arrRmAttachFile.push(v);
}         
Map:
vm.filesMapUpload = new Map();
for (var i = 0; i < e.length; i++) {
    vm.filesMapUpload.set(e[i].name, e[i]);
   
}
var fNames = '';
vm.filesMapUpload.forEach(function(value, key, map) {
    fNames = fNames + key + ":";
});
var rmID = $('#btnRemoveSetupFileCli').val();
vm.filesMapUpload.delete(rmID);
vm.filesArrayUpload = [];
vm.filesMapUpload.forEach(function(value, key, map) {
       vm.filesArrayUpload.push(value);
});

4.Reduce method

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

link:
https://www.freecodecamp.org/news/reduce-f47a7da511a9/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce


5.Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.


REF:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


Wednesday, February 22, 2017

Android and Architecture

Today we're announcing a guide to Android app architecture along with a preview of Architecture Components. Rather than reinventing the wheel, we're also recognizing the work done by popular Android libraries.

Closures & callback function javascript & jQuery

What is a closure?

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:
 

function showName (firstName, lastName) {


​var nameIntro = "Your name is ";

// this inner function has access to the outer function's variables, including the parameter​

​function makeFullName () {


​return nameIntro + firstName + " " + lastName;


}


​return makeFullName ();


}



showName ("Michael", "Jackson"); // Your name is Michael Jackson

Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.

Tuesday, February 21, 2017

Consuming a RESTful Web Service with Spring for Android

This Getting Started guide walks you through the process of building an application that uses Spring for Android's RestTemplate to consume a Spring MVC-based RESTful web service.

Compile và chạy ứng dụng rest server

You will build an Android client that consumes a Spring-based RESTful web service. Specifically, the client will consume the service created in Building a RESTful Web Servce.
Chạy spring boot rest: java -jar gs-rest-service-0.1.0.jar
The Android client will be accessed through an Android emulator, and will consume the service accepting requests at:
http://192.168.1.3:8080/greeting
The service will respond with a JSON representation of a greeting:
{"id":1,"content":"Hello, World!"}
The Android client will render the ID and content into a view.

Monday, February 20, 2017

Spring for Android Showcase

Introduction

This showcase includes an Android client and a Spring MVC server. Together these illustrate the interaction of the client and server when using Spring for Android. This Android project requires set up of the Android SDK. See the main README at the root of this repository for more information about configuring your environment.

Wednesday, December 7, 2016

JavaScript căn bản - part 1

1. Javascript là gì?

Javascript là ngôn ngữ lập trình của HTML và Web  chạy trên browser dưới dạng các script.


A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
  • Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
    The window object represents an open window in a browser.
  • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
  • Form object − Everything enclosed in the <form>...</form> tags sets the form object.
  • Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes. They have events, attributes, styles.
Here is a simple hierarchy of a few important objects -

Closures: Một số link tham khảo về Closures là

2. Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:
   1. HTML to define the content of web pages
   2. CSS to specify the layout of web pages
   3. JavaScript to program the behavior of web pages

3. Ví dụ 1: JavaScript can change HTML content

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html> 

4. Ví dụ 2: JavaScript can change CSS style

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>


</body>

</html> 

. Ví dụ 3: JavaScript can change HTML attributes

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>

</html>
<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>


</body>

</html> 
Tương tự, để hiển thị phần tử đang ở trạng thái hidden thì dùng đặt style.display='block'

7. Ví dụ 5: JavaScript với sự kiện onchange

<html>
<head>
<script type="text/javascript"> 
function updateInputValue(ishVal){
// ID of current element
var elementID = document.getElementById('CurrentUnitId').value;
document.getElementById(elementID).value = ishVal;
}

function updateTextBox(textboxID) {
//var txtID = document.getElementById(textboxID);
var orgID = document.getElementById('organizationSearchName');
orgID.value = '';
document.getElementById('CurrentUnitId').value = textboxID;
var tempElement = document.createElement("markActionURL");
tempElement.type = "hidden";
tempElement.value = '${actionUrl}';
document.getElementById('CommonTagsTreeChooserUnitID').appendChild(tempElement);
openTreeChooserDialog('organizationSearch','${actionUrl}');

}

function updateInput(ish){
   document.getElementById("fieldname").value = ish;
}

</script>

</head>
<body>
<input type="text" name="fieldname" id="fieldname" />  
<input type="text" name="thingy" onchange="updateInput(this.value)" />
</body>

</html>

this.value là value của phần tử đang xét.

8. Ví dụ 6: JavaScript chạy trưc tiếp một hàm cùng với trang web

Dùng đoạn mã sau nhúng vào body của trang html:
<script type="text/javascript">javascript:changeColumnWidthR2();</script>

khi load trang web, browser sẽ gọi hàm changeColumnWidthR2()。

Nội dung của hàm changeColumnWidthR2
<script type="text/javascript">
function changeColumnWidthR2(){
    $('#ColumnLabelEmployeeName').attr('style','width: 15%');
    $('#ColumnLabelCompany).attr('style','width: 35%');
    $('#ColumnLabelPosition').attr('style','width: 15%');
    $("#Output_Other_Help").html("<font color='red'><center>Click checkbox để chọn organization.</center></font>");
}
</script>


Ngoài ra, có thể gọi những hàm javascript mà không cần tới prefix javascript:
ví dụ:
<script>
    focusTextboxElement("frmSearch");
    pressSearchButton();

</script>

9. Điều kiện true/false với 1 biến số

var inputValue = null | undefined | NaN | empty string ("") | 0 | false
if(inputValue)
  alert('false');
else
  alert('true value');
=> trả về giá trị false cho biến số inputValue.

10. What does this mean: "undefined object property"?


What does this mean: "undefined object property"?
Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

var o = { a: undefined }
Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false
We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

11. JSON - check an Integer variable is valid

if(!(zoneId % 1 === 0)) {
    isZoneIdValid = false;
    result.code = 422;
    result.message = "zoneid = " + zoneId + " khong hop le";
}

if(jsonInput.maxItems >= 0)
    maxItems = jsonInput.maxItems;

12. JSON - check empty in javascript

- function isEmpty(value){
    return (typeof value === "undefined" || value === null || value.length === 0 || value === "undefined");
}
- hasOwnProperty
if(jsonInput.hasOwnProperty('maxItems')) {}


Popular Posts

Blog Archive