Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Use directive elements in Controller

Tags:

angularjs

I'm making a pagination app where the user can switch trough pages in the same window (pages get displayed beneath each other). Whenever someone changes the page, I want the window to scroll the right page

This is my page directive:

.directive('page', function () {
    return {
        restrict: "E",
        transclude: true,
        template: '<div ng-transclude></div>',
        link: function(scope, element, attrs) {
            /*
            * Better in controller, now the function has to be evaluated for every directive.
            * */
            scope.$on('pageChanged', function(event, page) {
                if (parseInt(attrs.number) === page) {
                    if (page === 1) {
                        window.scrollTo(100, element[0].offsetTop - 110);
                    }
                    else {
                        window.scrollTo(0, element[0].offsetTop - 60);
                    }
                }
            });
        }
    }

This works but now every directive listens to the pageChanged event and acts accordingly. I would prefer to only listen in the controller and let the controller scroll the window to the right page. (this way only one function has to be evaluated).

$scope.$on('pageChanged', function (event, pageNr) {
            $scope.currentPage = pageNr;
            /*
            * Scroll to the right page directive here
            **/
        });

To do this however I need to have access to the pages elements in the controller, is there a way to do this?

I was also looking for a method that could change the currentPage to the right page when the user scrolls the window.

like image 361
arnoutaertgeerts Avatar asked Aug 20 '13 09:08

arnoutaertgeerts


1 Answers

I think you shouldn't rely on events, but add a controller property to the directive object and declare the directive's controller there. Something similar to this (haven't tested it):

.directive('page', function () {
    return {
        restrict: "E",
        transclude: true,
        template: '<div ng-transclude></div>',
        controller: function ($scope, $element, $attrs, $transclude, otherInjectables) {
            // Add ng-click="goToPage(n)" directives on your HTML. Those should be inside of the <page> element for this to work.
            $scope.goToPage = function (page) {
                if (page === 1) {
                    window.scrollTo(100, $element[0].offsetTop - 110);
                }
                else {
                    window.scrollTo(0, $element[0].offsetTop - 60);
                }
        },
    }
});

For more information, consult the AngularJS documentation on directives.

like image 195
Alejandro García Iglesias Avatar answered Oct 26 '22 12:10

Alejandro García Iglesias