AngulerJS directive to scroll element by click

I'm going to use angular-scroll.

Load dependancies

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://oblador.github.io/angular-scroll/angular-scroll.min.js"></script>

JS initialization

var app = angular.module('TestApp', ['duScroll']);
app.controller('TestCtrl', function($scope, $http, $document){
    var items = [
        {title: 'Item 1', src: '/img/img1.png'},
        {title: 'Item 2', src: '/img/img2.png'}
    ]
});

Example of usage

<body ng-controller="TestCtrl">
    <ul id="items" class="list-unstyled" style="width: 40px; height: 96px; overflow:hidden;">
        <li ng-repeat="item in items"><img ng-src="{$ item.src $}" width="32"></li>
    </ul>
    <scrollarrows wrapper-id="items" items-length="{$items.length$}"></scrollarrows>
</body>

Clicking on arrows you can scroll items inside block with id items.

Code of directive

app.directive('scrollarrows', function() {
    return {
        restrict: 'E',
        template: '<i class="glyphicon glyphicon-chevron-up scrollarrows" ng-click="scrollUp()" ng-disabled="scrollTotal == 0"></i> <i class="glyphicon glyphicon-chevron-down scrollarrows" ng-click="scrollDown()" ng-disabled="scrollTotal == scrollMax"></i>',
        scope: {
            wrapperId: '@',
            itemsLength: '@',
            itemHeight: '@',
        },
        link: function(scope, element) {
            var wrapper = angular.element(document.getElementById(scope.wrapperId));
            var wrapperHight = wrapper.prop('offsetHeight');
            var total = 0, height = parseInt(scope.itemHeight), length = parseInt(scope.itemsLength);

            scope.scrollMax = length * height - wrapperHight;
            scope.scrollTotal = 0;

            scope.scrollUp = function() {
                scope.scrollTotal = (total - height >= 0) ? total - height : 0;
                total = scope.scrollTotal;
                wrapper.scrollTo(0, total, 300);
            }
            scope.scrollDown = function() {
                scope.scrollTotal = (total + height <= scope.scrollMax) ? total + height : scope.scrollMax;
                total = scope.scrollTotal;
                wrapper.scrollTo(0, total, 300);
            }
        }
    }
});
comments powered by Disqus