Angular Anchor Scroll without Promise

249 views Asked by At

I have am trying to use a very simple scrollTo in Angular 1.x. I have naviagation menu link which when clicked should scroll to a div#id. I can only get this to work with a 'promise'.

For example, this works:

<li><a href="#" ng-click="tracking()">Go to Tracking</a></li>


$scope.tracking = function() { // go to tracking when header button is clicked
        $http.get('/includes/modules/get_home_destinations.php')
        .then(function(reply){
            if (reply.data) {
                $scope.destinations = reply.data;
                $location.hash('home-tracking');
            }         
        });
    };

But this doesn't respond:

$scope.tracking = function() { // go to tracking when header button is clicked
     $location.hash('home-tracking');
};

It's as if a promise is required, but to get this to work on the simple click without the promise?

2

There are 2 answers

0
Muhammed Hasan Celik On BEST ANSWER

This is because of href="#" as I guess. Because firstly, href redirects page to "#" then the promise is executed with time delay and redirect back page to the desired location. But without promises, there is no time delay, code is executed immediately and href redirects page to '#' and page stuck there.

1
Chandru On

Hope this below code will be usefull :

in html file

<div id="home-tracking">
    <h1>Home Traking Content</h1>
</div>

<a ng-click="tracking()">Go to Tracking</a>

in controller file

angular.module('trackingApp').controller('TrackingCtrl', function($location, $anchorScroll) {
    $scope.tracking = function() {
          $location.hash('home-tracking');
          $anchorScroll();
    }
})