Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active December 20, 2015 20:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/6191419 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/6191419 to your computer and use it in GitHub Desktop.
JS: AngularJS Masonry Directive. http://plnkr.co/edit/ZuSrSh?p=preview
define(['angular', 'masonry', 'imagesLoaded', 'lodash'], function(angular, Masonry, imagesLoaded, _){
'use strict';
/**
* Masonry Directive for a wall of item.
* This directive is intended to be used along with ng-repeat directive.
* Put masonryWallDir on the container element and pass in a class selector for each item to be laid out.
* Pass in optional options via masonryWallOptions.
* Put the masonryItemDir next to ng-repeat directive on the item to be repeated.
* You're done!
*
* @param {String} masonryWallDir Class selector of each item
* @param {Object} masonryWallOptions Optional options that are directly passed into Masonry
*/
angular.module('Directives')
.directive('masonryWallDir', function(){
return {
controller: [
'$scope',
'$element',
'$attrs',
function($scope, $element, $attrs){
var wallContainer, masonryOptions;
wallContainer = $element[0];
masonryOptions = _.assign(
{},
$scope.$eval($attrs.masonryWallOptions),
{ itemSelector: $attrs.masonryWallDir }
);
this.masonry = new Masonry(
wallContainer,
masonryOptions
);
this.masonry.bindResize();
var self = this;
this.debouncedReload = _.debounce(function(){
self.masonry.reloadItems();
self.masonry.layout();
}, 100);
}
]
};
})
.directive('masonryItemDir',
function(){
return {
require: '^masonryWallDir',
link: function(scope, element, attributes, masonryWallDirCtrl){
imagesLoaded(element, function(){
if(scope.$first){
masonryWallDirCtrl.masonry.prepended(element);
}else{
masonryWallDirCtrl.masonry.appended(element);
}
});
scope.$on('$destroy', masonryWallDirCtrl.debouncedReload);
}
};
}
);
});
@CMCDragonkai
Copy link
Author

Douglas Jardine had an issue with modifying Masonry after it's been loaded. So he contributed his version:

$attrs.$observe('masonryWallOptions', function(actual_value) {
    masonryOptions = _.assign(
        {},
        $scope.$eval(actual_value), //$attrs.masonryWallOptions), 
        { itemSelector: $attrs.masonryWallDir }
    );

        self.masonry = new Masonry(
        wallContainer,
        masonryOptions
    );

    self.masonry.bindResize();

    self.debouncedReload = _.debounce(function(){
        self.masonry.reloadItems();
        self.masonry.layout();
    }, 100);
});

The above code replaces: https://gist.github.com/CMCDragonkai/6191419#file-masonrywall-directive-js-L29-L46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment