ng-scrollbar is not working with ng-repeat

后端 未结 4 992
庸人自扰
庸人自扰 2021-01-21 08:58

In my app I want to use a custom scrollbar for a div. So I used ng-scrollbar, it is working fine with static data. But whenever I get the data using ng-repeat it is not working.

4条回答
  •  -上瘾入骨i
    2021-01-21 09:09

    This might be a bit late.

    The problem is even though you have added the content to scope variable, angular has not finished adding p tags to your DOM. If you try a simple console log like

    console.log($('.well').find('p').length);
    

    After pushing content to $scope.me, you will understand what is happening. (Need jQuery at least to debug)

    The solution is far more complicated than you can imagine.

    STEP 1:

    Add a ng-controller to your ng-repeat (Yes. It is allowed)

    {{mi.name}}


    STEP 2: Define loopController

    demoApp.controller('loopController', function($scope) {
        $scope.$watch('$last', function(new_val) {
            new_val && $scope.$emit('loopLoaded', $scope.$index);
        });
    });
    

    This controller function is triggered whenever ng-repeat manipulates DOM. I'm watching $last which is a scope variable for ng-repeat. This will be set to true whenever, ng-repeat loads last element in DOM. When $last is set to true I emit one event loopLoaded. Since you are pushing values into $scope.me using a loop, this event will be triggered for every push.


    STEP 3: Event handling

    In your SimpleController (not simple anymore, eh?)

    $scope.$on('loopLoaded', function(evt, index) {
        if (index == $scope.me.length-1) {
            $scope.$broadcast('rebuild:me');
        }
    });
    

    Once all the p elements are loaded, index sent to event will be equal to $scope.me.length-1. So you call scroll rebuild. That's it.

    Here's a reference I used - AngularJS - Manipulating the DOM after ng-repeat is finished

提交回复
热议问题