AngularJS ng-repeat and Packery.js

2019-09-17 21:11发布

问题:

I am trying to implement packery in an angularJS application.

When I define the items manually one by one (see the commented html code), Packery works fine. When I try to do the same thing with an ng-repeat loop, packery does not work.

How can I make packery work with ng-repeat in an angularJS template?

The template:

<div class="item-container" workspace>

  <div class="module-sizer"></div>
  <div class="gutter-sizer"></div>

  <div
    ng-repeat="item in items"
    class="item">
         <!--my {{angular content}} here-->
  </div>

  <!-- this works: -->
  <!--
  <div class="item">
    item 1
  </div>
  <div class="item">
    item 2
  </div>
  <div class="item">
    item 3
  </div>
  <div class="item">
    item 4
  </div>
  <div class="item">
    item 5
  </div>
  <div class="item">
    item 6
  </div>
  <div class="item">
    item 7
  </div>
  -->

</div>

The angular directive, based on: http://codepen.io/gruntruk/pen/Cpewt/

myApp.directive('workspace', ['$rootScope', function ($rootScope) {
    return {

        constrain: 'A',

        link: function (scope, element, attrs) {

            element.ready(function () {

                var packery = new Packery(element[0], {
                    rowHeight: '.module-sizer',
                    itemSelector: '.item',
                    columnWidth: '.module-sizer'
                });

                angular.forEach(packery.getItemElements(), function (item) {
                    var draggable = new Draggabilly(item);
                    packery.bindDraggabillyEvents(draggable);
                });

                packery.layout();

            });

        }
    };
}]);

回答1:

Okay, I found the answer.

1) I had to use a directive with an event to be received by the controller

2) I had to add a setTimeout.

app.directive('lastRepeat', function () {
    return function(scope, element, attrs) {
        if (scope.$last) setTimeout(function(){
            scope.$emit('LastElement', element, attrs);
        }, 1);
    };
});