2014-05-08

[AngularJS] 製作 jQuery scrollTop scrollLeft directive

Html
<div jq-scroll-top="viewerScrollTop" 
      jq-scroll-left="viewerScrollLeft"
></div>

JavaScript
app.directive('jqScrollTop', ['$parse', function($parse){
    return function(scope, element, attrs) {
        /*解析並取得表達式*/
        var expr = $parse(attrs['jqScrollTop']);

        /*監聽變數異動,並更新到 element 上*/
        scope.$watch(attrs['jqScrollTop'], function(value) {
            element.scrollTop(value);
        });

        /*當 element 捲動時更新到變數上*/
        element.on('scroll', function() {
            expr.assign(scope, element.scrollTop());
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('scroll');
        });
    };
}]);

app.directive('jqScrollLeft', ['$parse', function($parse){
    return function(scope, element, attrs) {
        /*解析並取得表達式*/
        var expr = $parse(attrs['jqScrollLeft']);

        /*監聽變數異動,並更新到 element 上*/
        scope.$watch(attrs['jqScrollLeft'], function(value) {
            element.scrollLeft(value);
        });

        /*當 element 捲動時更新到變數上*/
        element.on('scroll', function() {
            expr.assign(scope, element.scrollLeft());
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('scroll');
        });
    };
}]);

0 回應: