How to use jQuery in Angular 2

First install jQuery with NPM: npm install --save jquery

Update scripts key in your angular-cli.json to include jQuery

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

You should stop angular-cli and rerun it using ng serve.

Now jQuery is available globally in the application. Whenever you need to use just declare $ or jQuery at the top like so:

import { Component, OnInit } from '@angular/core';  
// import line is this one
declare var $:any;
//declare var jQuery: any;

export default class Random implements OnInit {  
  ngOnInit() {
    // $ will be availble
    console.log($);
  }
}

 

Advertisements

jQuery THIS trap in Angular 2

Because of the access scope for jQuery, you must be careful when you use the jQuery in the  Angular. such as for this code  :

resultList  :string[] = [];
       myarray  :string[] = ['s1','s2','s3'];

       ............
                this.resultList.push('testS1');
                jQuery.each( this.myarray, function( index, v ) {
                        this.resultList.push(  v );
                });
       ...............

The error you will get will be :
Cannot read property ‘push’ of undefined

Correct way is:

       resultList  :string[] = [];
       myarray  :string[] = ['s1','s2','s3'];

       ............
                this.resultList.push('testS1');
                let __mythis = this;
                jQuery.each( this.myarray, function( index, v ) {
                        __mythis.resultList.push(  v );
                });
       ...............

Angular – How to pass data by the router link

Refer to google page of https://angular.io/docs/ts/latest/guide/router.html#!#navigate ,

I just give a myself example to show how it works. This is a master component that wswapill guide the router to a component link of  /itemdetail  and together pass one object – this.selectedItemObj to next page. (selectedItemObj  could contain the itemName, id, etc. inside.)

import { Router} from '@angular/router';
....constructor(
        private router: Router
    )...
....this.router.navigate( ['/itemdetail', this.selectedItemObj] );
...

And then  at the target component, we can try to get the router link parameters at the init stage to initialize the data:

import { ActivatedRoute, Router, Params } from '@angular/router';
...
constructor(
        private route: ActivatedRoute,
        private router: Router
    ) {... }
...
ngOnInit() {
        this.route.params.subscribe(
            params => {
                this.itemName = params['itemName'];
                this.item = + params['id'];
                // TODO, you can call your service to get more data based on the ID or name 
                   ...
                });
..........

If you do not need to do too much things after you get the params data, you can use the switchMap to do a simple service call before subscribe, refer to google link for the example there.

How to consume json object from Spring MVC controller input directly

By WZH

This is small note about the json input directly to Spring MVC controller side, jackson will auto convert it to Java object you want:

  1. Make sure has this jar added

 <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
  </dependency>

2.  Controller side

@RequestMapping(value = urlPatternController, method = RequestMethod.POST)
public @ResponseBody Person createPerson(@RequestBody Person jsonString) {
   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody – Covert Json object to java
@ResponseBody– convert Java object to json

3. JS client side :

 

$.ajax("<%=path%>/web/urlPatternController", {
                           type:'POST',
                           dataType: 'json',
                           data: person
                    })

 

Link can be refered

 

 

How to get the caret coordination in pix on the UI by JS

By W.ZH

The issue of this topic is to want to know the key caret position on the web UI, (not the mouse cursor ). Such as for my example , I have a text area to collect the input text, but I also want to show a piece of context menu at the position of the caret to do something for the text editor. So knowing the exact x and y position of caret is very import to match the text word in the area.

And I found this one should be the best after searching.

https://github.com/component/textarea-caret-position

Here is the example I created:

getCaretCoordinates will give you the top and left px of the caret relative to the textarea itself.  So we just need to find the offset of the parent element of the textArea and then easily caculate out the px position of the caret on a screen.

HTML code side:

111

 

JS code to detect the ctrl+Space key pressed and also find out the caret coordination.  You can replace my menu show part of code ( #mm) by whatever you want to do…

        // crtl+ space keys will show the context menu 
            $('#currArea').keyup(function (event) {
                if (event.keyCode == 32 && event.ctrlKey) {
                    // find the x and y for the caret
                    
                    var element = document.getElementById("currArea");
                    var tagParentOffsets = $('#currAnnoParent').offset();
                    
                    // use a plug to find the top and left 
                    var coordinates = getCaretCoordinates(element, element.selectionEnd, { debug: !true });

                    $('#mm').menu('show', {
                        top:  tagParentOffsets.top + element.offsetTop - element.scrollTop + coordinates.top + 'px',
                        left: tagParentOffsets.left + element.offsetLeft - element.scrollLeft + coordinates.left + 'px'
                    });
                }
            });

How to make EasyUI JS Datagrid to support filter and scrollview together

W.ZH

Issue: When you use the easyUI datagrid, you have millions of rows, you need to use pagination or scroll-view to support it.  But you might found that your filter will not work properly after you add scrollview or pagination feature.

You will find the filter may conflict with the pagination or table scroll feature.  Most common thing will see is filter sometimes work, but some times not. Problem occurs randomly on UI.

Reason: Most reason is because you want use the local filter but the datagrid data are gotten from remote/server side json. Then you will see this problem easily.

Solution: You need to run the filter and the pagination/scroll  both from server side or both from local. Here is some sample code I created to support the filter and scroll both together from remote server side.

Two more extension js files you need:

/resources/js/easyui/datagrid-filter.js">
/resources/js/easyui/datagrid-scrollview.js">

HTML for table:

<table id="data_list_table" style="height:750px"  ></table>

JS for load table

jQuery(document).ready(function() {
            $('#data_list_table').datagrid({
                url : '<%=path%>/web/sampleController/getSampleByPage',
                toolbar : '#data_list_table_toolbar',
                nowrap: true,
                fitColumns:true,
                singleSelect:true,
                rownumbers : true,
                view: scrollview,
                remoteFilter: true,
                pagination : false,
                autoRowHeight:false,
                pageSize : 30,
                columns:[[
                            {field:'sampleid',title:'DB ID',width:35},
                            {field:'samplename',title:'Slot Name',sortable :true, order : 'asc', width:110},
                            {field:'sampletype',title:'Slot Type',sortable :true, order : 'asc', width:95},
                            {field:'sampledesc',title:'Slot Description', width:250}
                        ]]
             });
               // filter for the table
             var dg = $('#data_list_table').datagrid().datagrid('enableFilter');
   });

So every time you load the table and also move mouse to scroll next page data, you will get the http request contains these data in the request:

sort
order
page
rows
filterRules – contains the filterRules data and you need to convert to your SQL where conditions.

here is a sample to process it in Spring and JAVA:

@RequestMapping(value = "/getSampleByPage", method = { RequestMethod.POST,
            RequestMethod.GET })
    @ResponseBody
    public EASYUIJSONTransport getSampleByPage(SearchInput search,
            HttpServletRequest request) throws Exception {
        int total = sampleService.totalCountSample();
        List<Sample> samples = searchbypage(search); // do by your self JPO access method

        return new EASYUIJSONTransport(total, slots);
    }
********************************************************
public class SearchInput {
    private String sort = "samplename";
    private String order = Common.sort_asc;
    private int page = Common.default_page;
    private int rows = Common.default_rows;
    private String filterRules = "";
.............................

}

Reference :

http://www.jeasyui.com/extension/datagrid_filter.php

http://www.jeasyui.com/tutorial/datagrid/datagrid27.php

http://www.jeasyui.com/extension/datagridview.php

Convert GoogleSites To WordPress

By W.ZH Apr 2016

Recently I setup this WordPress and tried to move my goolge sites articles to here. So here I  created a simple tool to read out the sites pages and convert them into the WordPress posts and keep the original dates of them.

I have shared my tools to GITHub at here:

https://github.com/WayneShare/GoogleSitesToWordPress

GoogleSitesToWordPress By Wayne.A tool to help convert your google sites pages to the WordPress posts.

  1. Export your google sites pages into a folder,use the tool of google-sites-liberation at this link https://github.com/sih4sing5hong5/google-sites-liberation by this tool, each page on sites will be created a index.html in a folder or subfolder.
  2. Find out your WordPress accounts and URL for XMLRPC API.
  3. Make the config properties files in our code, update the ToolConfig.properties file to your settings.
  4. Try to run the GoogleToWordPress.class to let it: a. search your folder to find out all index.html file b, extract the html content of your sites pages and convert them to posts for WordPress. c. write to WordPress via XMLRPC API.
  5. Feel free to change the code upon the needs. Java code is really simple and we use the lib of jwordpress of Bican to access the WordPress

Enjoy it if it is useful.