angular Scroll div on button click

2019-07-12 19:32发布

I'm just learning angular and have a problem i just can't figure out how to solve it.

I'm trying to achieve the following.


Tab A / Tab B / Tab C

.................................

Content in a fixed height Container


When i click a tab, some content is loaded via json and displayed in the container. Since its a lot of content i get a scrollbar.

What i want to do now is: Store the scrollTop Position for each Tab, so you can continue reading where you left when you switch tabs.

At the moment i have a directive on the content div, that triggers whenever the div gets scrolled, and stores the scrollTop Position in an array, related to the tab that is currently active.

app.directive("scrollPosition", function(){
    return{
    restrict: 'A',
    link: function(scope , element){
       element.bind("scroll", function(){
        scope.scrollPosition[scope.tab.categoryIndex]=element.scrollTop();

      });
    }
}
})

This works so far.

But i have no clue how to use this stored ScrollTop Value to set the div to that position when i click of one of the tabs.

Whats the proper angular way?

Using an ng-click on the tabs and then scroll the div? Using something like a $watch inside the directive to see which tab is clicked?

Help would be much appreciated, since i could only find examples where the whole document was scrolled, which is easy to address. But i just don't know how to get this relationship between the tab buttons and the div.

Thanks Markus

1条回答
叼着烟拽天下
2楼-- · 2019-07-12 20:13

Look into $anchorScroll. You can set a yOffset on it before call the function.

$anchorScroll.yOffset = 122; 
$anchorScroll();

https://docs.angularjs.org/api/ng/service/$anchorScroll

Update:

So I solved this. My first answer was too hasty.

Here is a link to plnkr(also embedded into post though): http://embed.plnkr.co/kwPkFDfyJctfPRFPPLyk

Scroll the first tab, click on the second tab, then back in the first.

I added a pos variable to the isolate scope of the directive and passed in scope variables from the main controller. This way the directive can set the scroll position on a two-way bound variable. The next time the tab is clicked on, the directive sets its the scroll position on its element to the last scrolled to position via its scope.pos variable. Hope this helps!

(function() {
  'use strict';

  var app = angular.module('TabsApp', [])
    .controller('TabsCtrl', ['$scope', function($scope) {

      $scope.tabs = [{
        "title": 'One',
        "url": 'one.tpl.html',
        "pos": 0
      }, {
        "title": 'Two',
        "url": 'two.tpl.html',
        "pos": 0
      }, {
        "title": 'Three',
        "url": 'three.tpl.html',
        "pos": 0
      }];

      $scope.$watch('tabs', function(val) {
        console.log("Yay!!! It's working! Val=" + val[0].pos);
      }, true);


      $scope.currentTab = $scope.tabs[0];

      $scope.onClickTab = function(tab) {
        $scope.currentTab = tab;
      };

      $scope.isActiveTab = function(tabUrl) {
        return tabUrl == $scope.currentTab.url;
      };
    }]);

  app.directive("scrollPosition", function() {
    return {
      restrict: 'A',
      scope: {
        pos: "="
      },
      transclude: false,
      link: function(scope, element) {

        element[0].onscroll = function() {
          scope.pos = element[0].scrollTop;
          console.log(scope.pos);
          scope.$apply();
        };


        element[0].scrollTop = scope.pos;
      }
    };
  });

})();
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  float: left;
  border: 1px solid #000;
  border-bottom-width: 0;
  margin: 3px 3px 0px 3px;
  padding: 5px 5px 0px 5px;
  background-color: #CCC;
  color: #696969;
}

#mainView {
  border: 1px solid black;
  clear: both;
  padding: 0 1em;

}

#viewOne, #viewTwo, #viewThree {
  overflow: scroll;
  height: 200px;
}

.active {
  background-color: #FFF;
  color: #000;
}
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css" />

</head>

<body>
  <div ng-app="TabsApp">
    <div id="tabs" ng-controller="TabsCtrl">
      <ul>
        <li ng-repeat="tab in tabs" ng-class="{active:isActiveTab(tab.url)}" ng-click="onClickTab(tab)">{{tab.title}}</li>
      </ul>
      <div id="mainView">
        <div ng-include="currentTab.url"></div>
        {{currentTab.pos}}
      </div>
      <script type="text/ng-template" id="one.tpl.html">
        <div id="viewOne" scroll-position pos="currentTab.pos">
          <h1>View One</h1>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
          <p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc.</p>
        </div>
      </script>
      <script type="text/ng-template" id="two.tpl.html">
        <div id="viewTwo" scroll-position pos="currentTab.pos">
          <h1>View Two</h1>
          <p>Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit amet arcu. Class aptent taciti sociosqu.</p>
        </div>
      </script>
      <script type="text/ng-template" id="three.tpl.html">
        <div id="viewThree" scroll-position pos="currentTab.pos">
          <h1>View Three</h1>
          <p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit amet
            arcu. Class aptent taciti sociosqu.</p>
        </div>
      </script>
    </div>
  </div>
</body>

</html>

查看更多
登录 后发表回答