1

My issue is that href retains scroll position, but I would like to have my links go to the top of the page; my current solution doesn't feel very DRY.

HTML:

<a href="" ng-click="goToPage()"></a>

JS:

app.controller("SomeController", function(..., $location) {
    //this ends up being repeated in many controllers
    $scope.goToPage = function() {
        $location.path('/some/page');
        window.scrollTo(0,0);
    }
});

Is there a way to make a directive like this?

<a href="" ng-link="'some/page'">

Now there should be no function explicitly defined in the controllers themselves.

According to this:

Can I make a function available in every controller in angular?

An alternative solution is that I can put a function inside $rootScope, and use it like this:

HTML:

<a href="" ng-click="goToPage('some/page')"></a>

JS:

app.run( function(..., $location) {
    $rootScope.goToPage = function(url) {
        $location.path(url);
        window.scrollTo(0,0);
    }
});

now I don't need to repeat the function inside each controller, but I thought this is a good place to avoid the $rootScope and learn about making directives (services?) if possible. Thanks!

Community
  • 1
  • 1
WBC
  • 1,854
  • 4
  • 21
  • 34

1 Answers1

2

You could just do this:

app.run(function($rootScope, $window) {
     $rootScope.$on('$routeChangeSuccess', function () {
         $window.scrollTo(0,0);
     });
});

and it will scroll to the top on any route change.

If you really want it as a directive:

angular.module('app')
    .directive('ngLink', ['$location', '$window', function ($location, $window) {
        return {
            restrict: 'A', //use as attribute 
            replace: false,
            scope: {
               'ngLink' : '@' //so you can do ng-link="some-page"
                              //instead of ng-link="'some-page'"
            },
            link: function (scope, elem) {
                 elem.on('click', function() {
                   $location.path(scope.ngLink);
                   //$window.location.href = scope.ngLink;
                   //you may have to use the line above depending
                   //on how your project is set up
                   $window.scrollTo(0,0);
                 });
            }
        }
    }]);
dave
  • 62,300
  • 5
  • 72
  • 93