AngularJS观察者没有约束/观看

时间:2016-01-12 15:41:36

标签: angularjs bind target

我正在尝试使用指令在列表中实现“无限滚动”功能,当html元素的滚动达到或超过可滚动高度的75%时,该指令应逐渐加载一组新的“订单”并将其附加到现有列表中。 不幸的是,当我滚动列表时,观察者不会触发。 该指令位于正确的标记中,当浏览器呈现该元素时,观察者仅在第一次触发侦听器功能。 奇怪的是,如果我改变路径然后我返回到列表所在的路径,则观察者开始正常运行并在每次执行滚动时触发侦听器功能。

<ol orders-loader class="orders-list">...</ol>

角:

(function () {
angular.
        module('myApp')
        .directive('ordersLoader', ['$window', '$timeout', 'ordersResource', ordersloaderDirective])

function ordersloaderDirective($window, $timeout, loading, ordersResource) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.orders = ordersResource; /*ordersResource use $resource to api calls
            and then stocks the data in a array exposed in the scope*/

            $timeout(function () {
                scope.$watch(function () { return element[0].scrollTop }, function () {
                    if (*the scroll exceedes more or less 75% of the total scrollHeight*/) {
                            /*asking for more orders*/                            
                    }
                });
            }, 0);
        }

    }
}

我无法弄清问题在哪里。

解决 正如 yeouuu 建议的那样,列表滚动事件后没有摘要周期,所以我补充道:

element.bind('scroll', function () {
                scope.$apply();
            });
<$>就在$ timeout函数之前。

1 个答案:

答案 0 :(得分:2)

每当在angularJs之外使用应该触发观察者的插件时,你需要明确地应用它们。否则Angular将不会意识到这些变化/事件。

在您的情况下,这意味着在事件发生后添加scope.$apply();

您编辑的解决方案:

element.bind('scroll', function () {
  scope.$apply();
});

此处可以找到有关范围生命周期的更多信息:https://docs.angularjs.org/guide/scope#scope-life-cycle