AngularJS 观察者未绑定/正在观察
AngularJS watcher not binding/ watching
我正在尝试使用指令在列表中实现 "infinite-scroll" 功能,当 html 元素滚动到该指令时,该指令应逐步加载一组新的 "orders"或超过可滚动高度的 75% 并将其附加到现有列表。
不幸的是,当我滚动列表时,观察者不会触发。
该指令位于右侧标记中,当浏览器呈现元素时,观察者仅在第一次触发监听器函数。
奇怪的是,如果我改变路径,然后我 return 到列表所在的路径,观察者开始正确运行并在我每次执行滚动时触发监听函数。
<ol orders-loader class="orders-list">...</ol>
angular:
(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 函数之前。
无论何时在 angularJs 之外使用应该触发观察器的插件,您都需要明确应用它们。否则 Angular 不会知道这些 changes/events.
在您的情况下,这意味着在事件之后添加 scope.$apply();
。
您编辑的解决方案:
element.bind('scroll', function () {
scope.$apply();
});
可以在此处找到有关作用域生命周期的更多信息:https://docs.angularjs.org/guide/scope#scope-life-cycle
我正在尝试使用指令在列表中实现 "infinite-scroll" 功能,当 html 元素滚动到该指令时,该指令应逐步加载一组新的 "orders"或超过可滚动高度的 75% 并将其附加到现有列表。 不幸的是,当我滚动列表时,观察者不会触发。 该指令位于右侧标记中,当浏览器呈现元素时,观察者仅在第一次触发监听器函数。 奇怪的是,如果我改变路径,然后我 return 到列表所在的路径,观察者开始正确运行并在我每次执行滚动时触发监听函数。
<ol orders-loader class="orders-list">...</ol>
angular:
(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 函数之前。
无论何时在 angularJs 之外使用应该触发观察器的插件,您都需要明确应用它们。否则 Angular 不会知道这些 changes/events.
在您的情况下,这意味着在事件之后添加 scope.$apply();
。
您编辑的解决方案:
element.bind('scroll', function () {
scope.$apply();
});
可以在此处找到有关作用域生命周期的更多信息:https://docs.angularjs.org/guide/scope#scope-life-cycle