|
| 1 | +/*! |
| 2 | + * angular-masonry 0.1.0 |
| 3 | + * Pascal Hartig, weluse GmbH, http://weluse.de/ |
| 4 | + * License: MIT |
| 5 | + */ |
| 6 | +(function () { |
| 7 | + 'use strict'; |
| 8 | + |
| 9 | + angular.module('wu.masonry', []) |
| 10 | + .controller('MasonryCtrl', function controller($scope, $element, $timeout) { |
| 11 | + var bricks = {}; |
| 12 | + var reloadScheduled = false; |
| 13 | + |
| 14 | + // Make sure it's only executed once within a reasonable time-frame in |
| 15 | + // case multiple elements are removed or added at once. |
| 16 | + function scheduleReload() { |
| 17 | + if (!reloadScheduled) { |
| 18 | + reloadScheduled = true; |
| 19 | + |
| 20 | + $timeout(function relayout() { |
| 21 | + reloadScheduled = false; |
| 22 | + $element.masonry('layout'); |
| 23 | + }, 0); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + this.appendBrick = function appendBrick(element, id, wait) { |
| 28 | + function _append() { |
| 29 | + if (Object.keys(bricks).length === 0) { |
| 30 | + // Call masonry asynchronously on initialization. |
| 31 | + $timeout(function () { |
| 32 | + $element.masonry('resize'); |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | + element.addClass('loaded'); |
| 37 | + if (bricks[id] === undefined) { |
| 38 | + // Keep track of added elements. |
| 39 | + bricks[id] = true; |
| 40 | + $element.masonry('appended', element, true); |
| 41 | + scheduleReload(); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + if (wait) { |
| 46 | + element.imagesLoaded(_append); |
| 47 | + } else { |
| 48 | + _append(); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + this.removeBrick = function removeBrick(id, element) { |
| 53 | + delete bricks[id]; |
| 54 | + $element.masonry('remove', element); |
| 55 | + |
| 56 | + scheduleReload(); |
| 57 | + }; |
| 58 | + }).directive('masonry', function () { |
| 59 | + return { |
| 60 | + restrict: 'AE', |
| 61 | + controller: 'MasonryCtrl', |
| 62 | + link: function postLink(scope, element, attrs) { |
| 63 | + var itemSelector = attrs.itemSelector || '.masonry-brick'; |
| 64 | + element.masonry({ itemSelector: itemSelector }); |
| 65 | + } |
| 66 | + }; |
| 67 | + }).directive('masonryBrick', function () { |
| 68 | + return { |
| 69 | + restrict: 'AC', |
| 70 | + require: '^masonry', |
| 71 | + link: function postLink(scope, element, attrs, ctrl) { |
| 72 | + var id = scope.$id; |
| 73 | + ctrl.appendBrick(element, id, true); |
| 74 | + |
| 75 | + scope.$on('$destroy', function () { |
| 76 | + ctrl.removeBrick(id, element); |
| 77 | + }); |
| 78 | + } |
| 79 | + }; |
| 80 | + }); |
| 81 | +}()); |
0 commit comments