When adding extra widgets to my array, Packery fails to function properly within AngularJS

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>

Answer №1

The issue at hand involves the binding of events to grid items by packery in order to facilitate layout and enable them to be 'draggable'. The following snippet is responsible for this functionality:

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

The current setup of your directive causes it to initialize packery & draggabilly with the above code and pckry.layout(); when the template initially loads, detecting any matching items with class .module. However, after this point, your application does not recognize any increase in the number of widgets.

To ensure proper initialization upon addition of widgets, you can pass the scope into the directive as shown below:

constrain: 'A',
scope: true,
link: // ...

In addition, you should include a $scope.$watchCollection on the array widgets like this:

$scope.$watchCollection('widgets', function() {
            // Call packery and draggabilly on elements here
});

You may consider moving the logic for initializing packery into a separate function for better code organization. It's worth noting that the $watchCollection will trigger upon the first execution of the directive, so all the necessary logic can be contained within it.

Lastly, remember that calling pckry.destroy(); beforehand might be necessary to achieve the desired outcome. While I'm unable to provide an example at the moment, I hope these suggestions serve as a helpful thought exercise!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the class of the parent element by referencing the child id in jQuery?

I want to trigger an alert on click from the child id <th id="first"> to the table(parent) class. alert($(this).parent('tr').attr('class')); This code helped me to get the class of the <tr>. However, when I try to get the ...

Having difficulty using JavaScript regex to replace the middle of content?

I am working with a text name[one][1][two][45][text] Through this pattern, I am able to extract the number "45" /(.*?)rows\]\[([0-9]*)(.*)/; Now, my challenge is how can I change the only 45 to a different digit? Using the same pattern and re ...

Choose the Range of Shapes in the ActiveSheet using the Excel function MyArray

When attempting to select shapes with specific conditions on a designated page number, and then group them together, an error message is displayed for "ActiveSheet.Shapes.Range(MyArray).Select." Sub group_all() Dim X, x_count, x_start, x_end As Integ ...

Comparing two numpy arrays to identify common elements

My current task resembles an SQL search scenario. I have a "table" that consists of the following 1D arrays (approximately 1 million elements) identified by ID1: ID1, z, e, PA, n There is another "table" containing the following 1D arrays (about 1.5 mill ...

Implementing Real-Time Search Feature Using AJAX

Exploring the world of search functions for the first time, I decided to implement an AJAX function to call a PHP file on key up. However, I encountered some strange behavior as the content in the display area was changing, but not to the expected content. ...

Utilizing NestJS to pass multiple IDs as parameters in an API

I am working with nestjs for the first time and I've been tasked with creating an API at http://localhost:8000/companies/4/5/8…. Does anyone know how to create this API using the GET(':id') method that can handle multiple parameters? ...

What is the best way to set up the user's editable information in the input field?

Is it possible for a user to edit their data? I have made the data accessible on this page, stored in information. I would like the user to see their data upon entering the view, such as their username or email, and be able to edit or delete it. I initiall ...

Troubleshooting issue with Angular's inability to loop through a multi-dimensional JSON

I recently started experimenting with Angular and decided to create a shopping cart application. I found a pre-made site template that organizes items into categories using the following structure: <div class="row"> <ul> <li>item1</li ...

Struggling with a 404 error when using Backbone's fetch method

I am currently facing a 404 error while attempting to use this backbone model node to fetch data from the server. Despite verifying that my files are correct, the issue persists var app = app || {}; app.NotesModel = Backbone.Model.extend({ url:' ...

Determine the position of the largest value within an array in C++, regardless of the presence of multiple maximum values

I have been working on a solution to find the index of the largest element in an array. However, I encountered an issue when there are multiple elements with the same maximum value in the array. I initially used std::max_element() to find the index, but it ...

React Native, state values are stagnant

I created an edit screen where I am attempting to update the post value through navigation v4 using getParams and setParams. However, when I modify the old value and click the save button, it does not update and no error is displayed. The old values still ...

An issue occurred during the hydration process, causing the entire root to switch to client rendering since the error occurred outside of a Suspense boundary

I've started seeing some errors and warnings: Error: An error occurred while hydrating. Since it happened outside of a Suspense boundary, the entire root will switch to client rendering. Error: Hydration failed due to initial UI not matching what was ...

How can I safeguard my HTML and CSS content from being altered using tools similar to Firebug?

Is there a method to deter the alteration of HTML and CSS components on a webpage using tools similar to Firebug? I have noticed that certain users are changing values in hidden fields and modifying content embedded within div or span tags for their perso ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...

Reverting button highlighting when another button is selected in Web development using CSS and Bootstrap

On my signup page, I have two buttons that control the display of corresponding containers. However, I encountered an issue where clicking a button changes its background color and keeps it changed even after selecting the other button. If I click the same ...

Each div in prevAlll() will have its own unique CSS background

In continuation of my initial query, which has now been resolved, you can find the original question here. JS: $(function() { var scaletext = { 1: 'SA', 2: 'A', 3: 'N', 4: 'Da', 5: 'SDa' } $(&a ...

Is it possible for the $.post function to overwrite variables within the parent function?

Recently, I delved into the world of JavaScript and my understanding is quite limited at this point. So, please bear with me as I learn :-) I am working on a basic booking system that saves dates and user IDs in MySQL. The system checks if a particular da ...

How come I'm encountering issues when trying to click on the "register-selection" button in my Bootstrap and JS setup?

I am facing a challenge while developing my website. I want to trigger an alert when the "register-selection" is clicked, but despite trying both Jquery and vanilla Javascript, I have not been successful. Even after searching online resources and ChatGPT f ...

Is there a way to transform Python's JSON object into an HTML table?

Creating a webpage using Flask and encountering some issues with Python syntax: @app.route('/uploads/<filename>') def uploaded_file(filename): reader = shapefile.Reader("./uploads/"+filename) fields = reader.fields[1:] field_names = ...

AngularJS Bindings Problem

As a newcomer to AngularJS, I have been working on creating a todo list. Through my research on Google, I was able to write the code successfully. Whenever I click the add button, whatever I type into the textbox gets added to the list (UL /li). However, ...