添加元素在年底滚动angularjs名单元素、年底、名单、angularjs

2023-09-13 03:46:17 作者:默 默、

我有一个要求,这是在一行上显示的元素列表,允许用户滚动,而当他滚动到最后,调用一个函数在此列表中添加元素。

I have a requirement which is to display a list of elements on one line, allow user to scroll, and when he scrolls to the end, call a function to add elements in this list.

我设法每行显示的元素,呼吁滚动结束的功能,添加元素在列表中,但问题是,我的观点不会显示新的元素,和滚动年底不工作了

I managed to display elements on a line, call function on end of scroll, add elements in the list, but the problem is, my view doesn't display the new elements, and the end of scroll doesn't work anymore.

我使用angularJS,我需要的是基本上无限水平滚动。

I am using angularJS, what I need is basically an infinite horizontal scrolling.

下面是我的code:  - HTML:

Here is my code : - html :

<div class="timeline">
  <div ng-repeat="t in test" class="content">
    qqq
  </div>
</div>

CSS:

.timeline {
  width: 500px;
  overflow-x: auto;
  white-space: nowrap;
}

.content {
  display: inline-block;
  width: 200px;
  height: 200px;
  background-color: red;
}

JS:

app.controller('timelineController', ['$scope', function($scope) {

    $scope.test = [];
    for (var i = 0; i < 10; i++) {
        $scope.test.push(i);
    }

    $(function () {
        $('.timeline').scroll(function () {
            if ($('.timeline').scrollLeft() == ($scope.test.length * 200 - 500)) {
                for (var i = 0; i < 10; i++) {
                    $scope.test.push(i);
                }
            }
        });
    });
}]);

我使用jQuery的,但我宁愿使用angularJS。不幸的是,我还没有发现任何可以解决我的问题。

I use jquery for that, but I would rather use angularJS. Unfortunately, I haven't found anything that could solve my issue.

这里是一个小提琴: https://jsfiddle.net/b67x9pog/

所有的想法都无任欢迎!

All ideas are more than welcome !

推荐答案

更​​新发生在角之外消化周期,所以它不知道更新$范围。你需要用在 $范围的更新。$适用()让角度了解变化。

The update is happening outside of the Angular digest cycle, so it's not aware of the update to $scope. You need to wrap the update in $scope.$apply() to let Angular know about the changes.

var app = angular.module('app', []);

app.controller('timelineController', ['$scope', function($scope) {

    $scope.test = [];
    for (var i = 0; i < 10; i++) {
        $scope.test.push(i);
    }

    $(function() {
        $('.timeline').scroll(function() {
            if ($('.timeline').scrollLeft() == ($scope.test.length * 200 - 500)) {
                $scope.$apply(function() {  // <--- $scope.$apply() added here
                    for (var i = 0; i < 10; i++) {
                        $scope.test.push(i);
                    }
                });
            }
        });
    });
}]);

在这个例子中,你还需要通过添加跟踪到 NG-重复来避免有重复键的问题:

In this example, you'll also want to add a track by to the ng-repeat to avoid issues with duplicate keys:

<div class="timeline">
    <div ng-repeat="t in test track by $index" class="content">
        qqq
    </div>
</div>