AngularJS: use directives in the controller

I am creating a pagination application where the user can switch the passage pages in one window (pages are displayed below each other). Whenever someone changes the page, I want the window to scroll the right page

This is my directive for the page:

.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 for the pageChanged event and acts accordingly. I would prefer only to listen in the controller and let the controller scroll the window to the desired page. (thus, only one function needs 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 page elements in the controller, is there any way to do this?

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

+8
angularjs
source share
1 answer

I think you should not rely on events, but add the controller property to the directive object and declare the control controller there. Something similar to this (not tested):

 .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); } }, } }); 

See the AngularJS directive documentation for more information.

+23
source share

All Articles