在我的应用程序中,我想为 div 使用自定义滚动条。所以我使用了 ng-scrollbar,它可以很好地处理静态数据。但是每当我使用 ng-repeat 获取数据时,它就不起作用。请在这方面帮助我。提前致谢。
myFile.html
<style>
.scrollme {
max-height: 300px;
}
</style>
<div ng-app="myapp">
<div class="container" ng-controller="myctrl">
<button class="btn btn-info" ng-click="add();">add</button>
<button class="btn btn-warning" ng-click="remove();">remove</button>
<div class="well" >
<div class="scrollme" ng-scrollbar bottom rebuild-on="rebuild:me">
<h1>Scroll me down!</h1>
<p ng-repeat="mi in me">{{mi.name}}</p>
</div>
</div>
</div>
</div>
myCtrl.js
var myapp = angular.module('myapp', ["ngScrollbar"]);
myapp.controller('myctrl', function ($scope) {
$scope.me = [];
for(var i=1;i<=20;i++){
$scope.me.push({"name":i});
}
var a = $scope.me.length;
$scope.add = function(){
$scope.me.push({"name":$scope.me.length+1});
$scope.$broadcast('rebuild:me');
}
$scope.remove = function(){
$scope.me.pop();
}
});
最佳答案
尝试将 broadcast
调用添加到 Controller 的末尾,以便它在 Controller 加载时触发。如果这不起作用,请尝试添加:
$timeout(function () {
$scope.$broadcast('rebuild:me');
}, 0);
// 0 optional, without it the time is assumed 0 which means next digest loop.
在 Controller 代码的末尾,而不是在 add 函数内。如果此方法有效但之前的方法无效,则意味着 ngRepeat 没有及时完成动态内容的渲染,以便 ngScrollbar 正确更新。
更新:通常,您可能还必须在超时时将广播包装在 add() 函数内。我这样说的原因是我怀疑发生了什么是您将数据添加到范围变量,然后在同一个函数调用中广播所有内容。可能发生的情况是,在 ngRepeat 看到更新的范围数据并添加其额外的 DOM 元素之前,广播事件被捕获并且滚动条重新计算。顺便说一句,如果您想在 add() 上重新计算滚动条,那么您也想在 remove() 上执行此操作。
所以你的添加函数会变成:
$scope.add = function(){
$scope.me.push({"name":$scope.me.length+1});
// wait until next digest loop to send event, this way ngRepeat has enough time to update(?)
$timeout(function () {
$scope.$broadcast('rebuild:me');
});
}
关于angularjs - ng-scrollbar 不适用于 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663917/