星期六, 6月 13, 2015

[AngularJS] 不透過type=reset來清除表單

記錄一下如何在angular清除表單內的值呢?
一般來說除了透過在頁面上放置一個按鈕類型為reset的效果最快。
但如果要在送出表單後,Server確定新增正確後,
再清除表單可自已新增一個resetForm的方法來處理。
以下是一個新建用戶的頁面來說明:


重設2按鈕是使用自訂的方法來清除表單資料,這裡需要額外注意type=mail資料驗證失敗是不會被寫入進$scope的,透過手動來清除,透過上圖可以清除看到$scope.user物件並無存到已輸入的錯誤文字

 $scope.resetForm = function(formModel) {
            logger.debug('resetForm');
            console.log(formModel);


            $scope.addForm.$setPristine();
            angular.copy({}, formModel);

            $scope.user.email = '';//解決email input無法清除的問題,email欄位要在通過規則後才會被model綁定
        };

頁面元素放入 ng-click="resetForm(user),user則為表單的物件
  <button type="button"
                                 ng-click="resetForm(user)" class="btn btn-default">
                                <i class="fa fa-refresh"></i> 重設2</button>

星期五, 6月 12, 2015

[CSS] 處理內部元素無法完全顯示的問題,當父元素加入overflow:hidden時

之前遇到頁面上做了一個contextmenu的選單效果,但一直被顯示時,選單會因為父元素裡面設了overflow:hidde,導致這個問題。


討論串位址:
http://stackoverflow.com/questions/3387489/make-child-visible-outside-an-overflowhidden-parent

This is an old question but encountered it myself.
I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")
If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.
If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.



[jQuery Plugins] fancybox 執行在1.9.x的jquery錯誤處理

處理一些新版jquery跑fancybox 1.3.4的處理方法:
討論位址:

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.
Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.
As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.

UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.
For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :
Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :
  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :
    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    and replace it by (EDITED March 19, 2013: more accurate filter):
    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msieinstances, if any), thanks joofow ... that's it!
Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanksfairylee for pointing out the extra closing bracket)
NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)
Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

星期二, 6月 09, 2015

[Javascript] 如果透過window物件來將字串轉換成執行程式

先前需要遇到不同狀況時,
呼叫不同含式,
但函式內部只是call不同api,
於是為了簡寫一點程式,利用字串的方法來取得函式物件,
可以使用window[你的函式字串]來轉換含式

           var runAPI = '';
                switch (reportType) {

                    case 'datastream':
                        runAPI = 'FUN_A';
                        break;

                    case 'avg':
                        runAPI = 'FUN_B';
                        break;

                    case 'max':
                        runAPI = 'FUN_C';
                        break;

                    case 'min':
                        runAPI = 'FUN_B';

                        break;

                }//end of switch

                //conv to real js function !!important
                var fnRunAPI = window[runAPI];

接著funRunAPI就變一個可執行的函式了


2015/10/21 更新

另外要使用物件或帶入參數也是可行的


window[你的函式字串](參數)

window[物件Class名稱][物件函式字串](參數)


星期日, 6月 07, 2015

星期六, 5月 09, 2015

[Java] Java專案的JS/CSS minify

針對Java專案js/css最小化相關open souces資源記錄

pack-tag

A JSP Taglib for delivering minified, combined and gzip-compressed resources (JavaScript and CSS).

https://github.com/galan/packtag

Jawr

https://github.com/ic3fox/jawr


Granule

Java JS/CSS optimization solution (tag and ant,servlet). Whitespace remover and Google Closure compilator integration
https://github.com/JonathanWalsh/Granule


wro4j

Free and Open Source Java project which brings together almost all the modern web tools: JsHint, CssLint, JsMin, Google Closure compressor, YUI Compressor, UglifyJs, Dojo Shrinksafe, Css Variables Support, JSON Compression, Less, Sass, CoffeeScript and much more. In the same time, the aim is to keep it as simple as possible and as extensible as

https://github.com/wro4j/wro4j



星期二, 4月 21, 2015

[CSS] backgroud 與 backgroud-image 小踩雷

今天在弄二層下拉選單時(以前都有美工拉好T_T),
在mouse hover的時候設定要改一下背景色,結果卻把a裡面設定的backgroupd-image ICON蓋掉了,
原來是用錯指令啦,記得要使用backgroupd-color

.sub-nav li a:hover,.sub-nav li:hover{
    color:  #000 !important;
/*    border-bottom:  2px solid  #58616d;*/

    /*background是設背景圖,會把icon換掉的,要改backgroupd-color即可*/
    /*background:#dfdfdf !important;*/ 
     background-color: #dfdfdf !important;
}

星期一, 4月 20, 2015

[AngularJS-3rd] ui-select 操作筆記

記錄一下ui-select這個元件的操作
https://github.com/angular-ui/ui-select

ui-select transclude 錯誤

遇到這個問題只要升級angular的版本到1.2.18即可:D
// Recreates old behavior of ng-transclude. Used internally.
        .directive('uisTranscludeAppend', function () {
            return {
                link: function (scope, element, attrs, ctrl, transclude) {
                    transclude(scope, function (clone) {
                        element.append(clone);
                    });
                }
            };
        })


[jQuery API] 如何讓元素透過tabindex來達到Focus效果

今天在實作一個下拉選單顯示與隱藏的效果(透過點擊一個按鈕)
當下拉選單出現時,設定呼叫focus(),反之在失去Focus時,會自動hide。

加入tabindex屬性,讓元素(div or ul)支援focus方法

//再focus執行前,加入tabindex屬性
  $dropdownMenu.attr('tabindex',-1).fadeIn().focus();

偵測被Focus的元素的方法

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

去除瀏覽器的tabindex外框

當你讓選單focus的時候,會發現外框出現的色框


可以透過以下css,讓border消失

:focus { 
    outline: none; 
}

參考


星期日, 4月 12, 2015

[Bootstrap 3] 替下拉式選單加上三角形的對話框圖

如果想讓bootstrap的下拉選單多了一個三角形的圖案的視覺效果, 可以加入二個虛擬元素 before與after,如下所示:

.dropdown-menu:before {
  position: absolute;
  top: -7px;
  left: 9px;
  display: inline-block;
  border-right: 7px solid transparent;
  border-bottom: 7px solid #ccc;
  border-left: 7px solid transparent;
  border-bottom-color: rgba(0, 0, 0, 0.2);
  content: '';
}

.dropdown-menu:after {
  position: absolute;
  top: -6px;
  left: 10px;
  display: inline-block;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #ffffff;
  border-left: 6px solid transparent;
  content: '';
}

效果

星期六, 4月 11, 2015

[Bootstrap 3] 讓Label顯示於input的左側

今天想讓Label配置在input的左側,可以參考以下作法,加了一個control-label即可。


http://stackoverflow.com/questions/18404003/bootstrap-3-label-on-the-left-side-instead-above-a-input-field



[AngularJS-3rd] UI-Router 常用筆記

本篇慢慢記錄UI-Router相關的操作心得

UI-Router $state帶參數轉頁

  
$state.go('admin.productlist.uuid', 
{
uuid: product.FD_CurrentFilePathHash
});
 
// Admin page for productlist/:uuid
   $stateProvider
    .state('admin', {
     abstract: true,
     template: "",
     data: {
      authorizedRoles: [USER_ROLES.admin]
     }
    })
.state('admin.productlist.uuid', {

    /*manage user page */
    url: '/productlist/:uuid',

    views: {

     // the main template will be placed here (relatively named)
     // replace unnamed view '
' in this state's parent state, 'home'. '': { templateUrl: 'partials/global.index.html' }, //viewname@statusname // the child views will be defined here (absolutely named) 'header@admin.productlist': { templateUrl: 'partials/global.header.html', controller: 'HeaderCtrl' }, 'main_body@admin.productlist': { templateUrl: 'partials/product_dm/productlist.body.html', controller: 'ProductListCtrl' }, // for column two, we'll define a separate controller 'footer@admin.productlist': { templateUrl: 'partials/global.footer.html' } }, data:{ pageTitle: '產品DM' } });

星期五, 4月 10, 2015

[AngularJS] 小踩雷筆記: select option 綁定

當我們使用select做資料綁定的時候,需要注意一下綁型的變數型別是什麼字串或數值。
今天遇到的問題是,從db撈回來的select 設定的值是字串(String),但元件上綁定為數值(Int)
所以在設定model綁定的時候忘記轉成字串,就會發現綁定失敗XD

示意圖(圖好像合成錯張了,紅色是這次的注意的重點)


星期四, 4月 09, 2015

[UI-Bootstrap] 小踩雷筆記 Tabset元件的scope操作

記錄一下使用Tabset取得控制child scope變數的筆記:
由於Tabset會建立child scope,
所以想要存在tab內部的scope變化除了用 $parent.scope變數 (如果又巢狀的scope可能會發生錯誤例外),
也可以在parent controller宣告一致的變數,就能方便取值了。
以下這個Tabset的範例可以參考:
http://plnkr.co/edit/vclolFBfF7QMQAQgNmiL?p=preview


範例目的:
Justified這個tab裡面的input,一但值被改變,外面的parent scope會一起連動。




在tabset內綁定了一個parent scope宣告的model(model.selection)
<div ng-controller="TabsDemoCtrl">
  {{model.selection}}
  <tabset>
    <tab heading="Justified">
      <input ng-model="model.selection">
    </tab>
  </tabset>
</div>



宣告一個model的物件在parent scope,所以當tab裡面的input變動時,就容易取到變動的值了。
angular.module('plunker', ['ui.bootstrap']);
var TabsDemoCtrl = function ($scope) {
  $scope.tabs = [
    { title:"Dynamic Title 1", content:"Dynamic content 1" },
    { title:"Dynamic Title 2", content:"Dynamic content 2", disabled: true }
  ];

  $scope.model = {selection: ''};
  $scope.options = ['a', 'b', 'c', 'd'];

  $scope.alertMe = function() {
    setTimeout(function() {
      alert("You've selected the alert tab!");
    });
  };

  $scope.navType = 'pills';
};


https://github.com/angular/angular.js/wiki/Understanding-Scopes
https://github.com/angular-ui/bootstrap/issues/1553

星期五, 4月 03, 2015

[AngularJS] 多個信箱驗證的directive實作

記錄一下多個信箱驗證的directive實作。
.directive('multimails', function() {

    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl, ngModel) {

            var validator = function(value) {
                // console.log('validator: ' + value);
                if (value != '' && typeof(value) != 'undefined') {
                    var splitMailsArr = value.split(';');
                    // .filter(function(el) {return el.length != 0});
                    for (var i = 0; i < splitMailsArr.length; i++) {
                        var currMail = splitMailsArr[i];
                        // console.log('currMail: ' + currMail);
                        if (currMail != '') {
                            if (/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test(currMail)) {
                                ctrl.$setValidity('multimails', true);
                                // console.log('pass');

                            } else {

                                ctrl.$setValidity('multimails', false);
                                // console.log('no pass');
break;
                            }
                        }

                    }
                    return value;

                }

            };

            //驗證規則的順序
            ctrl.$parsers.unshift(validator);
            ctrl.$formatters.unshift(validator);
        }
    };
})

[GIT] 改壞了怎麼回到上一個版本

記錄一下GIT如何回到上一個版本的指令集

 Reverting Working Copy to Most Recent Commit To revert to previous commit, ignoring any changes:

git reset --hard HEAD

where HEAD is the last commit in your current branch Reverting Working Copy to an Older Commit To revert to a commit that's older than the most recent commit: # Resets index to former commit; replace '56e05fced' with your commit code
git reset 56e05fced  # Moves pointer back to previous HEAD git reset --soft HEAD@{1}

 git commit -m "Revert to 56e05fced" # Updates working copy to reflect the new commit git reset --hard

http://stackoverflow.com/questions/4114095/revert-to-previous-git-commit


另一篇Apple大大建議

cherry-pick跟reset + rebase (有點難懂XD)

https://blog.wu-boy.com/2009/12/git-how-to-remove-file-and-commit-from-history%E5%A6%82%E4%BD%95%E7%A7%BB%E9%99%A4-commit-%E6%AD%B7%E5%8F%B2%E7%B4%80%E9%8C%84/

[Javascript 茶包筆記] 簡單列表網頁的小函式

最近有客戶需要列印網頁的內容,於是找到了簡單的方法:D
//列印網頁
function printPage(text){
 
 var text= document;
 print(text);
}

星期五, 3月 27, 2015

[AngularJS] 小踩雷筆記: ng-class的css name使用-符合

如果你的class name使用了-符號,搭配使用ng-class時,請加上''符號,不然則會失效
請參考: http://stackoverflow.com/questions/15557151/ngclass-style-with-dash-in-key
After hours of hacking around, it turns out the dash gets interpolated! Quotes are needed.
 class="icon-home" ng-class="{'icon-white': someBooleanValue}">
I hope this helps someone from tearing their hair out.
UPDATE:
In older versions of Angular, using a backslash also does the trick, but not in the newer versions.
 class="icon-home" ng-class="{icon\-white: someBooleanValue}">
The former is probably preferred, since you can search for it in your favorite editor.

星期六, 3月 14, 2015

[AngularJS] 小踩雷筆記: button鈕點擊一直發生submit form的動作

今日踩雷小筆記: 如果你在form表單裡放了button鈕,並自行綁定ng-click方法時,如果html的button忘記加入type="button", angular將會貼心幫你觸發form submit XD

星期四, 3月 12, 2015

[Java] JPA 使用IN查詢

由於不習慣用jpa來操作db,第一次要使用in查詢式就踩雷了。
成功的方法如下:

  String cmd = "SELECT d FROM Device d  WHERE d.agentId IN :agentId";
            Query query  = entityManager.createQuery(cmd);
            query.setParameter("agentId", dealAgentIds);

備註: 

  • 不要把 :agentId多包一個括號,例如(:agentId),會炸給你看的。 
  • d.agentId是你產生結構裡面的欄位命名,不要用原本database的欄位。

星期五, 2月 06, 2015

[Angular] ng-src造成的infinite loop

目前在介面上顯示圖片列表時,因為圖片的網址加了random的參數來解決cache的議題,
但會產生infinite loop的error,打開console可以看到。
找到了Stackoverflow以下解譯這個的原因。

http://stackoverflow.com/questions/17222526/angular-js-in-ng-src-causes-infinite-loop
Well I think the problem is the getRandom function returning a different value every time it's called. Here's what happens:
  1. Angular call your function
  2. Gets the value
  3. See's it's different from the previous value
  4. Marks the cycle as dirty
  5. After the cycle is finished it re-runs the cycle thus getting a new value ...
The idea would be to have getRandom give discreet values over a period of time. For example only give a new value every 1, 10, 30 sec whatever you see fit.
This advice applies to many things, actually. Angular provides no guarantees about how many times it will call your functions that are found in bindings. So you need to make them fast and also you need to make sure that for the same input they return the same output(most times, though in this case it might be justified).
Also consider exactly when/how the image might change and if the actual changes can be triggered by something else consider only creating a new result value for getRandom only when the actual changes are triggered(ex: user uploads a new profile image, a timer executes, etc)
UPDATE: Can't replicate it in plunker using Chrome

解決的方法可以利用一個timer來透過記錄上一次變更的時間差來避免一直檢查的問題。




$scope.lastMillis = new Date().getTime();
     $scope.getRandom=function(){
         var curMillis = new Date().getTime();
         if (curMillis-$scope.lastMillis>5000) {
             $scope.lastMillis = curMillis;
         }
         return $scope.lastMillis;
     };

星期三, 2月 04, 2015

[Andorid] Mac版Eclipse ADT 安裝擷圖

骨灰級Eclipse安裝ADT圖文擷取記錄 :D

安裝ADT外掛,輸入網址

[CSS] IE8 顯示背景圖的icon的解決方法

遇到IE8的背景圖跑不出來的問題,另外ie8也看不懂 background-position 與 background-size

「background-size」是 CSS3 才有的進階語法,ie9後才有支援
.nav-icon-devicemgmt{
    background: url('../images/icons/nav-icon-devicemgmt.png') no-repeat left  ;
}

/*IE8可跑*/
.nav-icon-devicemgmt{  
    background-size: 32px 32px;
    background-image:url('../images/icons/nav-icon-devicemgmt.png') ;
    background-repeat:  no-repeat;
    background-position:  left ;
    background-position-x: 5px;
}

星期二, 2月 03, 2015

[jQuery API] IE8 隱藏column後表格寬度異常解決方法

昨天遇到ie8在表格的column隱藏時,表格的寬度未自動變動的問題。
慘況如下圖記念擷圖


找到這個作者的解法,透過變動display的屬性成inline-talbe,再透過setTimeout再把dispaly重設,表格的寬度就會正常了。


[CSS] IE8 border無法正常顯示

記錄一下處理ie8有關border無法正常顯示議題

/*.tblList tr td{
     position: relative;fix ie8 border issue
}
*/
先前的版本為了讓border的寬度能在ie8顯示,於是加了position:relative,但卻造成了後面版本的border卻顯示不出來

星期三, 1月 28, 2015

[Android] Android Studio 安裝記錄

最近要開始把玩Andorid,由於新手入門大家都建議不用完Eclipse ADTXD,
直接換Android Studio開發可能對長遠比較好,加上AS的功能與性能似乎幹爆Eclipse。
以下是安裝過程中炸掉的處理方法

安裝步驟

Step1: 遇到安裝JDK前會爆炸的話,請先下載這個補丁XD
http://support.apple.com/kb/DL1572?viewlocale=zh_TW&locale=en_US
Step2: 安裝JDK
Step3: 指定AS要用的JDK路徑,之後就一直下一步Next

網路上額外找的相關JDK的安裝路徑
For different types of JDKs or installations, you will have different paths.
On Mac OS X Mavericks, the path I found as following:
1) Built-in JRE default:
 /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
2) JDKs downloaded from Apple:
 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/
3) JDKs downloaded from Oracle:
/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home

Step4: 開始享用

參考

http://blog.ccc99.tw/2014/10/os-x-1010-java.html

星期二, 1月 20, 2015

[Java] Unable to load class for JSP 炸掉筆記

20150204更新:
最後發現有重覆的jar甘擾造成慘劇!!

  • jasper-compiler-5.5.23.jar
  • jasper-runtime-5.5.23.jar
  • jsp-2.1-6.1.14.jar
  • jsp-api-2.1-6.1.14.jar



好死不死遇到Unable to load class for JSP ,
手記這個bug的處理情況, 問了google大神也一堆人遇到
但沒統一的解法,有的人是用到的jar有衝突還是缺之類的,還是classpath跑掉blabla
目前的狀況整個IDE新舊專案的JSP都無法編譯。
索性就用重灌ide的方法,結果執行的時候也爆了。
原來一灌的時候,忘了設Tomcat的VM Options(會導致libs無法載入太多而炸掉)
接著就能跑了....


炸掉的error



星期一, 1月 19, 2015

[NetBeans] 設定Utf-8編碼

預設的netbeans好像沒有gui設定utf-8編碼開啟檔案,可以透過修改設定檔的方式來解決

步驟:


1. 打開設定檔:
C:\Program Files (x86)\NetBeans 7.2.1\etc\netbeans.conf

2. 找到netbeans_default_options參數

3. 加入-J-Dfile.encoding=UTF-8


星期二, 1月 06, 2015

[NetBeans] 自動刷新專案目錄結構

記錄一下刷新netbeans專案目錄的ide操作

手動掃描變動

"Source" > "Scan for External Changes"

自動掃描變動

ide預設好像是開啟的:d


[NetBeans] Project Group功能筆記

如果有多個專案版本要同時在netbeans運行可以使用Project Group這個功能來切換不同的project,記錄有關於這功能的事項:D

設定檔路徑

找不到怎麼砍掉舊有的project group可以到以下路徑

%USER_HOME%\AppData\Roaming\NetBeans\<版本號>\config\Preferences\org\netbeans\module‌​s\projectui\groups

裡面有產生java的properties檔案來記錄相關資訊,檔名為 .properties

星期日, 12月 21, 2014

[jQuery Plugin] required depends 讓驗證欄位基於其他特地條件成立

如果你使用jquery validator要讓required規則依特地條件成立才驗證的話, 可以使用呼叫的depends方法,並自訂規則:D
$('#ProspectDtlFrm').validate({ 
    rules: {
        prsptEmail: {
            required: {
                depends: function(element) {
                    return ($('#prsptHomePhone').val() == '' && 
                            $('#prsptBusinessPhone').val() == '' && 
                            $('#prsptMobilePhone').val() == '');
                }
            }
        }    
    }, 
    messages: { 
        prsptEmail: 'Please enter your first name'
    } 
});

Reference
jquery validate depends rule

星期四, 12月 18, 2014

星期二, 12月 09, 2014

[jQuery Mobile] 設定select menu的初始化

想要指定select menu的初始化的話只要設定val就好了,但要記得refresh一下

範例:

  $('#frmAnalytics_ReportGroup').val('avg').selectmenu('refresh');

星期四, 12月 04, 2014

[jquery plugin] jquery validator 驗證多個選取盒checkbox

常用的需求,怕忘記直接寫個範例記一下。
以下範例介紹如何透過jquery validator來驗證多個checkboxes,
可以透過minlength參數來指定選取數量

HTML

欲代理區域:
                        <input type="checkbox" id="north" name="area" value="north" /> 北部
                        <input type="checkbox" id="central" name="area" value="central" /> 中部
                        <input type="checkbox" id="south" name="area" value="south" /> 南部
                        <input type="checkbox" id="east" name="area" value="east" /> 東部


JS範例

$validatedContact
   = $("#contactForm").validate({
    rules: {

     //共同 checkbox
     area: {
      required: true
      ,minlength: 2
     }
},
messages:{
area: {
      required: "區域未選取"
      ,minlength: "至少選取二個區域"
     }
},
 submitHandler: function(form) {
}
});


結果



[jQuery plugin] 移除已初始化過的jquery validator

今天有一個頁面需求,需求在切換不同type的時候,變更不同的form的顯示的欄位, 為了方便就是重設jquery validator,可以透過以下範例重設form的validator

範例

$("#contactForm").data("validator", null);
  $("#contactForm").unbind("validate");
  $("#contactForm").removeData("validator")
  $("#contactForm").unbind("submit");//必需移除submit的行為,不然會多重綁定

星期三, 12月 03, 2014

[Javascript] Timer議題: setTimeout 與 setInterval的筆記

最近用timer來實作dashboard相關的機制,順便查一查筆記一下:d

字面上說明

Timeout  ==>逾時
Interval  ==>間隔


定義:

Javascript的計時功能提供了setTimeout與setInterval這兩種用法,執行後會取得一個Timer ID。
要取消計時可以用的分別是clearTimeout()和clearInterval(),然後把執行後取得的Timer ID殺掉即可

兩者差別:


setTimeout()只做一次;setInterval()會不停的的調用函數。



運作原因:

由於javascript是只有單一執行緒,因此只是告訴Js在某一段時間後,再插入執行你指定的函式








星期二, 11月 18, 2014

[PHP] 西元日期轉中文年月日

如果有需要將西元日期轉換的話,可以不用拆解字串的方式。
可參考內建的date函數即可

echo date('Y年n月d日',strtotime('2014-11-18')); 

星期一, 11月 17, 2014

[jQuery API] JSON SyntaxError: Unexpected token s

今天call同事的api,發現http status都是200正確,但都跑到$.ajax的error handler

17 Nov 2014 17:39:07,698 [DEBUG] [frmDeviceMgmt] jqXHR.responsetext: undefined log4javascript.min.js:155
17 Nov 2014 17:39:07,700 [DEBUG] [frmDeviceMgmt] textStatus: parsererror log4javascript.min.js:155
17 Nov 2014 17:39:07,700 [DEBUG] [frmDeviceMgmt] errorThrown: SyntaxError: Unexpected token s

查了一下原來是回傳的JSON格式是驗證錯誤的關係,踩雷共勉之:D

星期四, 11月 13, 2014

[Javascript] 日期增加運算

常用的增加時間運算函式,有興趣的朋友可以選用。可以自行設定Interval,非常方便:D
Reference: http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object


 function dateAdd(date, interval, units) {
        var ret = new Date(date); //don't change original date
        switch(interval.toLowerCase()) {
            case 'year'   :
                ret.setFullYear(ret.getFullYear() + units);
                break;
            case 'quarter':
                ret.setMonth(ret.getMonth() + 3*units);
                break;
            case 'month'  :
                ret.setMonth(ret.getMonth() + units);
                break;
            case 'week'   :
                ret.setDate(ret.getDate() + 7*units);
                break;
            case 'day'    :
                ret.setDate(ret.getDate() + units);
                break;
            case 'hour'   :
                ret.setTime(ret.getTime() + units*3600000);
                break;
            case 'minute' :
                ret.setTime(ret.getTime() + units*60000);
                break;
            case 'second' :
                ret.setTime(ret.getTime() + units*1000);
                break;
            default       :
                ret = undefined;
                break;
        }
        return ret;
    }

星期日, 11月 02, 2014

[Angular Directive] 取代傳統Alert的 ngSweetAlert


ngSweetAlert是基於sweetAlert的套件中的套件XD
比傳統的alert效果美觀太多了,下一個專案再來套用看看 :D

http://oitozero.github.io/ngSweetAlert/#/home

[jQuery Plugin] 時間範圍的Slider元件



想要slider效果的時間選擇器的話,可以試試這個JQRangeSlider

http://ghusse.github.io/jQRangeSlider/demo.html

[AngularJS] Retrieve JSON Data的key與data

一般使用ng-repeat的時候,除了有一般Array的結構之外,
有時API回傳的結果可能需要透過JSON DATA內部的Key結構來綁定。

今天的Case是要綁定一個問卷:D 資料結構長這個


為了讓元素的name id不一致也用了nested ng-repeat如何拿$index的方法,範例如下:

使用ng-init可以將第一層的迴圈$index透過 qTitleIndex取得
    

    <form id="investQuestionnaireForm">
     <div id="investQuestionnaireList"
      ng-controller="MyQuestionnaireCtrl" class="dialog-moduleContent msgBoxDetail">
   <div class="question-list">
    <ul >
     <li ng-repeat="(qTitle, ansList) in questionnaireList"
      ng-init="qTitleIndex = $index">
      <div>{{qTitle}}</div>
      <ul class="answerlist">
       <li ng-repeat="ans in ansList">
        <input type="radio" name="{{qTitleIndex}}_ans_{{$index}}" value="{{ans}}" /> {{ans}} <br/>
       </li>
      </ul>
     </li>
    </ul>

   </div>
     </div>
最後示意
 

星期六, 11月 01, 2014

[AngularJS] 使用jquery來呼叫Angular scope 方法與更新變數

想在舊的jQuery專案內呼叫Angular的方法與變數,可以在jquery中使用以下方法取得scope

var ngScope = angular.element(document.getElementById('元素ID')).scope();

ngScope即可以操作原本在ng內的方法與變數了,在透過jquery更新完變數後,記得要呼叫$apply來告知Angular裡面的變數的值已改變了!!

參考以下完整範例:



星期四, 10月 23, 2014

[Raphael.js ] 讓Morrisjs 支援Pie chart與水平bar chart

最近要套用morrisjs這套基於Raphael.js 的畫圖函式庫,發現了缺少了Pie Chart與水平bar chart功能,不過已經有二個fork這專案的人實作了,有興趣的人可以自已把這二個需求合在一起 :D

Pie Chart

https://github.com/tiraeth/morris.js

提供Pie chart的新圖形實作,不過不是merged到最新的master,使用的話,donut chart的hover顯示的文件位置會不一樣

PR Issue:
https://github.com/morrisjs/morris.js/pull/149

Bar Chart

https://github.com/JelteF/morris.js
支援水平的bar chart

星期六, 10月 11, 2014

[WordPress plugin] 顯示所有產品類別title過長的問題

今天發現使用顯示產品類別的short code中的title好像會長出很多換行空白,
因為就順便找一個原始碼的呼叫方式,進入點可以從這個檔案 includes/class-wc-shortcodes.php 開始, 所以就順利找到對應的產品列表原始碼位置 templates/content-product_cat.php 更詳細的資訊可以透過 http://oik-plugins.eu/woocommerce-a2z/ 來協助你追原始碼 :D

星期日, 10月 05, 2014

[WordPress Plugin] Woocomerce 顯示產品分類到首頁

Woocommerce內建提供簡單的語法讓使用者可以在自訂的頁面顯示產品分類
找到這篇討論串的解法: https://wordpress.org/support/topic/show-only-top-level-product-category-on-home-page


***
[product_categories number="12" parent="0"]
Set the parent paramater to 0 to only display top level categories.

如果要秀全部的分類的話,把number設 number="" 即可
***
經過測試是可以正常執行的,官方shortcode的文件裡面也找的到這行指令XD (RTFM)
顯示的效果如下:
當然預設的指令碼只會顯示如上圖的效果,如果模更進階的顯示的話,Wootheme提供你額外付錢的外掛:D,效果就比較靈活,如下圖所示。


有這樣需求的朋友可至此購買 










星期四, 10月 02, 2014

[jQuery Plugin] 撰寫jQuery plugin的寫作樣式

太久沒寫jQuery外掛了,找了一些資料來複習一下。
這篇文章記錄一下自已喜歡用的jquery plugin寫作方式。
初學者建議讀一下這篇: http://learn.jquery.com/plugins/

外掛功能


  1. 保持jQuery物件鏈結 (非常重要)
  2. 提供公有方法(有時候在init plugin之後,可能會需要公有方法能變更plugin的行為或屬性)
  3. 提供預設的參數設定
  4. 儲存產生plugin 物件的參考 (基於第二個方法)

方法一: 類似bootstrap的解法

最後參考這篇 Things I learnt creating a jQuery Plugin (Part I),作者也基於這個寫作方式,寫了一個bootstrap的tagger外掛: https://github.com/acanimal/tagger.js

;(function($) {
    //define plugin name
    var pluginName =  'jqueryPlugin';
    
    //create plugin class
    function Plugin (element,options){
        
        this.el = element;
        this.$el = $(element);
        
        this.options = $.extend({}, $.fn[pluginName].defaults, options);
       
        //constrctor
        this.init();
        
        return this;
    };
    
    Plugin.prototype.name = pluginName;
    Plugin.prototype.version =  '0.0.1';
    
    Plugin.prototype = {
        
        init : function(){
            
            var plugin = this;
        },
        
        /**
         * The 'destroy' method is were you free the resources used by your plugin:
         * references, unregister listeners, etc.
         *
         * Remember to unbind for your event:
         *
         * @example
         * this.$someSubElement.off('.' + pluginName);
         *
         * Above example will remove any listener from your plugin for on the given
         * element.
         */
        destroy: function() {

            // Remove any attached data from your plugin
            this.$el.removeData();
        },
        
         /**
         * Write public methods within the plugin's prototype. They can 
         * be called with:
         *
         * @example
         * $('#element').jqueryPlugin('somePublicMethod','Arguments', 'Here', 1001);
         *  
         * @param  {[type]} foo [some parameter]
         * @param  {[type]} bar [some other parameter]
         * @return {[type]}
         */
        pubMethod : function(){
            
        }
        
    }
 
    /**
     * This is a real private method. A plugin instance has access to it
     * @return {[type]}
     */
    var privateMethod = function() {
        console.log("privateMethod");
        console.log(this);
    };
    
    // Plugin wrapper around the constructor,
    $.fn[pluginName] = function(options) {
        
        var args = arguments;

        if (options === undefined || typeof options === 'object') {
            // Create a plugin instance for each selected element.
            return this.each(function() {
                if (!$.data(this, 'plugin_' + pluginName)) {
                    $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
                }
            });
        } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
            // Call a pluguin method for each selected element.
            if (Array.prototype.slice.call(args, 1).length == 0 && $.inArray(options, $.fn[pluginName].getters) != -1) {
                // If the user does not pass any arguments and the method allows to
                // work as a getter then break the chainability
                var instance = $.data(this[0], 'plugin_' + pluginName);
                return instance[options].apply(instance, Array.prototype.slice.call(args, 1));
            } else {
                // Invoke the speficied method on each selected element
                return this.each(function() {
                    var instance = $.data(this, 'plugin_' + pluginName);
                    if (instance instanceof Plugin && typeof instance[options] === 'function') {
                        instance[options].apply(instance, Array.prototype.slice.call(args, 1));
                    }
                });
            }
        }
    }

     /**
     * Names of the pluguin methods that can act as a getter method.
     * @type {Array}
     */
    $.fn[pluginName].getters = ['pubMethod'];
    
     /**
     * Default options
     */
    $.fn[pluginName].defaults = {
         defaultOption: "I'm a default option"
    };
    
})(jQuery);

其他你感興趣的文章

Related Posts with Thumbnails