我是 AngularJS 的新手,在执行 jQuery custom content scroller 时我遇到了一个问题进入我的应用程序。
我需要更新滚动条,当我用 Angular 更新内容时,滚动条有一个 update
方法。我的问题是,我不知道在哪里调用它。内容的标记如下:
<div class="scroll-list nice-scrollbars">
<ul class="gallery clearfix">
<li class="extra-alt" ng-repeat="item in relatedItems.data">
...
</li>
</ul>
</div>
我试图在 Angular 的 $http.post
的成功分支中调用更新方法:
$scope.relatedItems = $http.post($scope.url, {
'filterType': 'related', 'film': id
}).success(function() {
$(".nice-scrollbars").mCustomScrollbar('update');
});
这没有用,我认为是因为当调用成功方法时, View 内容还没有更新(我可以使用 alert
功能看到它,数据在关闭后出现对话框)
我能够使滚动条工作的唯一方法是使用滚动条的高级属性来观察内容的变化(这些是传递给滚动条的选项):
var scrollbarOpts = {
scrollButtons:{
enable:true
},
advanced:{
updateOnContentResize: true
//@TODO: get rid of this, correctly find where to call update method
}
}
这是不好的做法,因为这个选项会降低整个脚本的性能。 我想知道,根据需要调用更新 DOM 所需的 jQuery 方法的正确位置在哪里,或者这种绑定(bind)如何在 AngularJS 中正确完成查看更改?
最佳答案
DOM 操作应该在指令(而不是 Controller )中完成。该指令应该 $watch() 您的模型进行更改,并且 watch 回调应该执行 jQuery DOM 操作。有时在 Angular 更新/修改 DOM 之后(但在浏览器呈现之前)需要 $evalAsync 来运行 jQuery 代码。如果你想在浏览器呈现之后执行某些操作,请使用 $timeout
。参见 this answer ,我在其中提供了一个 fiddle ,展示了如何将指令用于 $watch() 模型属性,并且我在模拟 fetch() 函数中使用了 $evalAsync。
对于您的特殊情况,我建议您首先在指令中尝试以下操作:
scope.$watch("relatedItems.data", function() {
$(".nice-scrollbars").mCustomScrollbar('update');
});
如果不行,试试这个:
scope.$watch("relatedItems.data", function() {
scope.$evalAsync( // you might need to wrap the next line in a function, not sure
$(".nice-scrollbars").mCustomScrollbar('update')
);
});
关于javascript - 更改 View 时如何从 AngularJS 调用 JQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14002864/