当用户在角度js中滚动到div顶部时如何显示警报?

use*_*513 5 angularjs angularjs-directive angularjs-scope ionic-framework ionic

你好,请问如何在角度js滚动到div的顶部时显示警告,当用户滚动到底部时也是如此.实际上我知道如何使用if(this.scrollTop === 0)在jquery中实现这一点.但我是使用具有角度js的离子框架.所以你可以告诉我当用户滚动到顶部并显示警报时如何获取事件.

这是我的傻瓜 http://plnkr.co/edit/8bqDi69oiBKTpDvCaOf6?p=preview

<body ng-controller="MyController">
<div style="width:90%;height:150px;border:1px solid red;overflow:auto;overflow-y: scroll">
<div ng-repeat="n in name">{{n.name}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

seb*_*ier 7

Angular不会为您提供任何内容,您只需要在元素上绑定一个滚动事件.在我当前的项目中,我刚刚在我的控制器中创建了一个事件:

var container = angular.element(document);
container.on('scroll', function() {
    if (container.scrollTop() > 1000) {
        $('#scroll-top-button').addClass('show');
    } else {
        $('#scroll-top-button').removeClass('show');
    }
});
// in your case angular.element(document) should be your div instead of document
Run Code Online (Sandbox Code Playgroud)

它确实表现得很好(我希望if滚动事件花费一些资源但不是真的).

角度指令

简单的方法是定义一个指令来绑定一个滚动事件并查看位置.根据您的代码:

angular.module('ionicApp', ['ionic'])
  .directive("scrollable", function() {
    return function(scope, element, attrs) {
      var container = angular.element(element);
      container.bind("scroll", function(evt) {
          if (container[0].scrollTop <= 0) {
              alert('On the top of the world I\'m singing I\'m dancing.');
          }
          if (container[0].offsetHeight + container[0].scrollTop >= container[0].scrollHeight) {
              alert('On the bottom of the world I\'m waiting.');
          }
      });
    };
  })
  .controller('MyController', function($scope, $element) {
    $scope.name = [{ ... }];
  });
Run Code Online (Sandbox Code Playgroud)

然后在HTML中添加指令

<div scrollable style="width:90%;height:1...
Run Code Online (Sandbox Code Playgroud)

在你的plunker(v5)上更新了一个适用我的版本,并且对于全局兼容性似乎非常强大.它的水平低;)

替代图书馆

如果您想实现更深层次的功能,可以使用像waypoint这样的库

Waypoints是一个库,可以在滚动到元素时轻松执行函数. http://imakewebthings.com/waypoints/

它工作得非常好,非常轻,因为v3.0是免费的jQuery:D.我知道一些硬核前端设计师使用它而没有任何性能问题.