简体   繁体   中英

How to implement historyAPI with AngularJS?

I am trying to build a prototype on lines of qz.com.

Here is the approach:

  1. Make a function call to load next piece of content on scrolling to bottom of the page.
  2. Same function would change the url using $location.path(url) or window.history.pushState()
  3. On scrolling upwards, either of the two will change the url based on the section in display.

I am stuck at point 2. Whenever I call $location or pushState, the page reloads and goes in the loop.

Here is the code:

Controller

controller('BlogCtrl', function ($scope, $location, $http) {
$scope.blogs = [];
var counter = -1;
$scope.loadNext = function() {      
  $http.get('/api/blogs').success(function(data) {
    //console.log(counter);
    $scope.blogs.push(data[counter]);
    //$location.path('blog/'+data[counter].url);
    //window.history.pushState('blog/'+data[counter].url);
  });
  counter+=1;
}
$scope.loadNext();

})

Directive

directive('scrollLoad', function () {
return function (scope, elm, attr) {
    // Scroll should have been there instead of hover event.
    // For some reason, scroll wasn't being detected, hence used hover function.
    // It is essentially a hack. Need to revisit this piece.
    elm.on('hover', function() {
      window.onscroll = function(ev) {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            scope.$apply(attr.scrollLoad);
        }
      }
    });
}

});

html

div
  div(scroll-load="loadNext()", ng-repeat="blog in blogs")
    h1 {{blog.title}}
    p {{blog.content}}

link to repo: https://github.com/fotuzlab/two1/

If you have suggestions for another approach, please answer here

Answering self.

Not sure of the logic here, but moving the HTML from partial to index.html worked.

This piece is now part of project Sarus with a modified approach. https://github.com/srijanlabs/sarus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM