After spending a significant amount of time searching for a solution to my problem, I stumbled upon some code related to packery that surprisingly worked perfectly.
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: '.module',
columnWidth: '.module-sizer'
});
angular.forEach(packery.getItemElements(), function(item) {
var draggable = new Draggabilly(item);
packery.bindDraggabillyEvents(draggable);
});
packery.layout();
});
} }; }]).
Initially, everything was working fine with an array of widgets where I used ng-show to hide/show them. But now, instead of using ng-show, I decided to dynamically add and remove widgets from an empty initial array.
.controller('WidgetCtrl', ['$scope', function ($scope) {
$scope.counter = 0;
$scope.current = 0;
$scope.widgets = [];
$scope.addWidget = function(name){
var widgets = {
widget1: {name: 'widget1', id: ''},
widget2: {name: 'widget2', data: {dataVariable: 'some data'}, id:''}
};
var widget = widgets[name];
if (widget) {
$scope.widgets.push(widget);
$scope.widgets[$scope.current].id = $scope.widgets.length-1;
console.log('index of the last widget added: ' + $scope.widgets[$scope.current].id);
$scope.current++;}
The issue now is that only the widgets initially in the array can be dragged. Any widgets added later do not work. I've been exploring concepts like $scope.apply and recompiling directives in Angular, but I'm uncertain if they relate to my current problem.
<div class="module-container" workspace>
<div class="module-sizer"></div>
<div class="gutter-sizer"></div>
<div class="module" ng-repeat='widget in widgets'>
<div dynamic-widget='widget.name' data='widget.data'> </div>
</div>
</div>