Transfer objects from subordinate to master controller using draggable and droppable directives

I am working on a project that involves two directives, draggable and droppable. These directives use jQuery UI functions to enable drag-and-drop functionality on elements. In my setup, the draggable items are in a controller that has a parent controller containing a droppable div. I need help figuring out how to remove an item from the child controller's item list and add it to the parent controller's list, as well as removing the item from the draggable list on screen and incrementing the length of the droppable div.

If you'd like to take a look at my code, I have created a jsfiddle for reference:

http://jsfiddle.net/huNpS/1/

Here is the structure of the HTML:

<body ng-app="myApp">
    <div ng-controller="parentCtrl">
        <div id="dropzone" data-index="1" droppable>
            {{dropped_items.length}}
        </div>
        <div ng-controller="childCtrl">
            <div ng-repeat="item in items"
                data-index="{{$index}}" class="note" draggable>
                    {{item.title}}
            </div>
        </div>
    </div>
</body>

And here is the JavaScript code:

var app = angular.module('myApp', []);

app.controller('parentCtrl', function ($scope){
    var dropped = [
            {id:1, title:'Note 1'},
            {id:2, title:'Note 2'},
            {id:3, title:'Note 3'}
        ];
    $scope.dropped_items = dropped;

});

app.controller('childCtrl', function ($scope){
    var data = [
            {id:4, title:'Note 4'},
            {id:5, title:'Note 5'},
            {id:6, title:'Note 6'},
            {id:7, title:'Note 7'},
            {id:8, title:'Note 8'}
        ];

    $scope.items = data;

});

app.directive('draggable', function() {
    return {
        restrict:'A',
        link: function(scope, element, attrs) {
            element.draggable({
                revert:true
            });
        }
    };
});


app.directive('droppable', function($compile) {
    return {
        restrict: 'A',
        link: function(scope,element,attrs){
            element.droppable({
                drop:function(event,ui) {
                    var dragIndex = angular.element(ui.draggable).data('index');
                    var dropIndex = angular.element(this).data('index');
                    console.log(dragIndex);
                    console.log(dropIndex);

                    console.log(scope);
                    scope.$apply();
                }
            });
        }
    };
});

Answer №1

It appears that your jsfiddle is not functioning properly. One solution could be to avoid using a child controller, allowing access to the same scope. Is it necessary in this case?

If needed, you might consider setting up events and utilizing $.emit or $.broadcast on the $rootScope, then establishing a listener on the childCtrl to remove it from the list after it's dropped.

EDIT:

The updated jsfiddle link showing the corrected code: http://jsfiddle.net/huNpS/2/

I have eliminated the childCtrl and adjusted the code accordingly:

var app = angular.module('myApp', []);

app.controller('parentCtrl', function ($scope) {
    $scope.dropped_items = [
        {id: 1, title: 'Note 1'},
        {id: 2, title: 'Note 2'},
        {id: 3, title: 'Note 3'}
    ];

    $scope.items = [
        {id: 4, title: 'Note 4'},
        {id: 5, title: 'Note 5'},
        {id: 6, title: 'Note 6'},
        {id: 7, title: 'Note 7'},
        {id: 8, title: 'Note 8'}
    ];


});

app.directive('draggable', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.draggable({
                revert: true
            });
        }
    };
});


app.directive('droppable', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.droppable({
                drop: function (event, ui) {
                    var draggedElement = angular.element(ui.draggable);
                    var dragIndex = draggedElement.data('index');
                    var dropIndex = angular.element(this).data('index');

                    scope.items.splice(dragIndex, 1);
                    scope.dropped_items.push(draggedElement.data('obj'));

                    console.log(dragIndex);
                    console.log(dropIndex);

                    console.log(scope);
                    scope.$apply();
                }
            });
        }
    };
});

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

Can you identify the primary parameter used in the Parse.User.signUp() method?

Utilizing Parse.com as the database for my app, I am working on streamlining the code in my signup view. user.set("username",$scope.user.email); user.set("email",$scope.user.email); user.set("password",$scope.user.password); user.signUp(null, ...

The onClick function designed to trigger the Material UI dialog box is experiencing functionality issues

Is there a bug in the component? The material-ui dialog-box sometimes pops up on button click and shows the target value perfectly, but other times it doesn't. I am passing the value on the icon onclick event - (e) and using it in the onClick function ...

The issue encountered while attempting to utilize jspdf for exporting data

Currently, I am working on developing a web application using angularJS in combination with asp.net. My main goal is to export data into a PDF file, but unfortunately, I am facing some challenges in achieving this. While browsing on StackOverflow, I came ...

Utilizing a callback to modify a local variable in JavaScript

Below is my jQuery code: function checkHotelExists(value, col) { var url = base_url + 'ajax/checkuniquehotel'; var response = false; $.get(url, {hotelname:value}, function(data){ if (data === 'true&apos ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

Tips for utilizing a button within a hyperlink in a React component:

I am new to react and have been working on the following code: import {NavLink as Link} from 'react-router-dom' return ( <div> {posts.map((actualData, index) => ( <Link to={'/' + actualData.id}> <d ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

What is the method for assigning a value to a variable in xhr.setRequestHeader?

I'm working on setting a value to the variable in xhr.setRequestHeader(Authentication, "Bearer" + parameter); with xmlhttprequest. Can you provide guidance on how to effectively pass a value to the variable within xhr.setRequestHeader? ...

What are the strategies used by AngularJS's official website to create SEO-friendly pages?

If you're interested in seeing how AngularJS.org presents pre-rendered content to search engine bots and scrapers, take a look at http://docs.angularjs.org/?_escaped_fragment_=/tutorial/step_09 I'm intrigued by the implementation strategy used f ...

Managing individual HTTP responses within Angular 6

I currently have 15 HTTP requests being sent to the API individually. Instead of waiting for all requests to finish processing (especially one that can take a few minutes), I want to handle responses as they come in. On the service side: findOneByOne ...

Accessing UPI apps such as Google Pay through deep linking from a web application

I am currently exploring the possibility of deep-linking to individual UPI apps, like Google Pay, that are installed on a user's phone. The goal is for users to be seamlessly redirected to their preferred UPI app when they click on the respective icon ...

What is the best way to trigger the code within my useEffect React hook to execute again upon refreshing the page?

I'm encountering an issue where the value of states is becoming 'undefined' after refreshing the page. Within my useEffect hook, I am generating a random number to select a question object from an array. Everything works smoothly on the ini ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

The data points on the Google Maps heatmap are not visible

We are working on developing a server side application that will utilize the Google Maps API to create weighted heat maps for visualizing data. Check out the Google Maps API documentation for Heat Maps here Despite successfully displaying the map, my Jav ...

The click event fails to trigger while trying to parse external HTML

Currently, I am working on a project that requires me to load HTML from an external file and insert it into an existing div element. Although the process is successful overall, I have encountered an issue where the .click() events do not trigger when click ...

Implementing a vertical tabindex change in Material UI Dialogue table

My material UI dialogue contains a table: <Dialog open={open} onClose={handleClose} maxWidth={'xl'} aria-labelledby='scroll-dialog-title' aria-describedby='scroll-dialog-description' disa ...

Trouble updating document with MongoDB updateOne when using ID as filter

I need to update a property value of a specific document by sending a request to my NextJs API using fetch. // Update items in state when the pending time in queue has passed, set allowed: true items.map((item) => { const itemDate = new Date(item.adde ...

Is it possible for Sequelize to utilize a getter or setter within a find query?

When it comes to storing and querying email addresses in my database, I always opt for lowercase strings to prevent duplicate emails such as <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="077274627547627f666a776b62d48ed88e5"> ...

Occasionally, the Array.filter() method might strip away every element within the array

This situation is really frustrating me. The goal is to have the newArray return all elements except the one where the two ids match, as specified in the code. However, when I add objects to the array and then try to remove them one by one, the results are ...

Exploring the functionality of the onClick event handler in React

As a beginner in React, I am currently immersing myself in learning the framework from scratch. While I have successfully constructed some basic components for a restaurant website, I am encountering challenges when it comes to comprehending event handling ...