rearranging nodes from multiple arrays into a single array and then repositioning them within the parent array using angularjs

[![enter image description here][1]][1]I am working with AngularJS and I have multiple arrays named list1, list2, and list3. Each array is used in a different list. Within my application, there are two buttons and two divs - the left div displays elements from one of the arrays, while the right div displays elements from another array. When I click on an element in the left div and press the right button, that element should be removed from the left div and moved to the right div. Similarly, when I click on an element in the right div and press the left button, that element should be removed from the right div and inserted back into the left div. Additionally, any changes made should reflect in the parent array where the element was originally located.

Here is the HTML code:

<p ng-repeat="item in list1" id="attr">{{item}}</p>
   <button id="btn-right" ng-click="add()">rig</button>
   <button id="btn-left">left</button>

And here is the Angular code snippet:

$scope.list = ['date', 'birth'];
$scope.list1 = ['date', 'birth'];
$scope.list2 = ['date', 'birth'];
$scope.select=[];

$scope.insert=function(item,list){
    attribute= item;
    $scope.naml=list;
    console.log(naml);
};

$scope.add=function()
{
    var index=$scope.naml.indexOf(attribute);
    $scope.naml.splice(index, 1); 
    $scope.select.push(attribute);
    attribute=null;
}

Answer №1

angular.module("stack", [])
    .controller("move", function($scope) {
        // this.apps = features;
        $scope.leftList = [1, 2, 3];
        $scope.rightList = [4, 5, 6];
        var left, right;
        $scope.getLeft = function(item) {
            left = item;
        }
        $scope.getRight = function(item) {
            right = item;
        }
        $scope.ltr = function() {
            console.log("left ", left);
            if ($scope.leftList.length) {
                $scope.leftList.forEach(function(each, index) {
                    if (each === left) {
                        $scope.leftList.splice(index, 1);
                    }
                });
                $scope.rightList.push(left);
                left = "";
            }
        }
        $scope.rtl = function() {
            console.log("right ", right);
            if ($scope.rightList.length) {
                $scope.rightList.forEach(function(each, index) {
                    if (each === right) {
                        $scope.rightList.splice(index, 1);
                    }
                });
                $scope.leftList.push(right);
                right = "";
            }
        }
    });
.left,
.right {
    width: 10%;
    display: inline-block;
}

.butltr,
.butrtl {
    display: inline-block;
}
<!DOCTYPE html>
<html ng-app="stack">

<head>
    <title>stack</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>

    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body ng-controller="move">
    <div class="left">
        <div ng-repeat="item in leftList track by $index" ng-click="getLeft(item)">{{item}}</div>
    </div>
    <button class="butltr" ng-click="ltr()">ltr</button>
    <button class="butrtl" ng-click="rtl()">rtl</button>
    <div class="right">
        <div ng-repeat="item in rightList track by $index" ng-click="getRight(item)">{{item}}</div>
    </div>
    <script type="text/javascript" src="controller.js"></script>
</body>

</html>

I have made some aesthetic updates. Your feedback is appreciated.

Answer №2

If you want to implement this functionality, here is one way to do it:

Below is the HTML Page code:

<head>
    <style type="text/css"> 
        .red {
            color: red;
        }
</style>
</head>
<body ng-controller="MyCtrl">
<div style="float:left;border: solid;width: 48%;" align="center">
    <p ng-repeat="item in list1" ng-click="insert(item,'left'); 
toggle = !toggle" ng-class="{'red' : toggle}">{{item}}</p>
</div>

<div style="float:right;border: solid; width: 48%;" align="center">
    <p ng-repeat="item in list2" ng-click="insert(item, 'right'); 
toggle = !toggle" ng-class="{'red' : toggle}">{{item}}</p>
</div>

<div align="center">
    <button id="btn-right" ng-click="takeRight()">Right</button>
    <button id="btn-left" ng-click="takeLeft()">Left</button>
 </div>
</body>

Here is the Javascript part:

$scope.list1 = ['dateleft', 'birth'];
$scope.list2 = ['dateright', 'death'];
$scope.itemsOnLeft=[];
$scope.itemsOnRight=[];

$scope.insert=function(item, to){
    switch(to) {
        case "left":
            var index = $scope.itemsOnLeft.indexOf(item);
            if ( index != -1)   {
                $scope.itemsOnLeft.splice(index, 1);
            }   
            else {
                $scope.itemsOnLeft.push(item);
            }

            break;
        case "right":
            var index = $scope.itemsOnRight.indexOf(item);
            if ( index != -1)   {
                $scope.itemsOnRight.splice(index, 1);
            }   
            else {
                $scope.itemsOnRight.push(item);
            }                   
            break;
        default:
            console.log("Error in inserting");
    }
    };

    $scope.takeRight=function()
    {
        for (var i = 0; i < $scope.itemsOnLeft.length; i++) {
            var item = $scope.itemsOnLeft[i];
            var index = $scope.list1.indexOf(item);
            $scope.list1.splice(index, 1); 
            $scope.list2.push(item); 
        }
        $scope.itemsOnLeft.length = 0;              
    };

    $scope.takeLeft=function()
    {
        for (var i = 0; i < $scope.itemsOnRight.length; i++) {
            var item = $scope.itemsOnRight[i];
            var index = $scope.list2.indexOf(item);
            $scope.list2.splice(index, 1); 
            $scope.list1.push(item); 
        }
        $scope.itemsOnRight.length = 0;
    };  

Please keep in mind that using ng-Repeat for displaying two lists does not allow duplicates in a list. If you try to move an item to a destination where it already exists, an error may occur.

I hope this helps with what you're looking to achieve!

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

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Express 4 Alert: Headers cannot be modified once they have been sent

I recently upgraded to version 4 of Express while setting up a basic chat system. However, I encountered an error message that says: info - socket.io started Express server listening on port 3000 GET / 304 790.443 ms - - Error: Can't set headers ...

The Double Negation operator

While reading a book, I came across this code snippet: !!(document.all && document.uniqueID); I'm wondering why the double not operator is used here. Doesn't the && operator already convert the result to a Boolean? ...

Adjust the size of an image to fit within a set height row using CSS grid

I have a container with fixed width and height where I want to display an image and some text. My goal is to have the text appear first, followed by the image filling up the remaining space in the container. Check out the image below for reference: Exampl ...

Using the async.waterfall function in an Express application

Query: I'm encountering an issue with my express.js code where, upon running in Node.js, an empty array (ganttresult) is initially displayed. Only after refreshing the browser do I obtain the desired result. To address this problem, I have attempted ...

Using JSON data to populate an HTML page

I'm currently working on a project that involves creating a "Twitter" page. The idea is to utilize the JSON file available at to display some of its content. However, I'm facing an issue where my page only shows the table headers and nothing els ...

Tips for utilizing Material Design Lite for an input button

I have a HTML document that incorporates Material Design Lite 1.3 elements: <div id="submit-gs-req-form"> <div class="demo-card-wide mdl-card mdl-shadow--2dp"> <div class="mdl-card__title"> <h2 class="mdl-car ...

Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library. One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came acr ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

Dynamically showcasing content in an HTML table

Having trouble with this code snippet. It's supposed to iterate through array objects and display them in an HTML table. The third row should have buttons, but nothing is showing up. Can you spot the issue? Here's the HTML code: <html> & ...

Video with dynamic sizing doesn't adapt properly

I successfully achieved my main goal, which was to have a background video at the top of my page. However, I am facing an issue with making the video responsive. Currently, as I decrease the screen size, the video shrinks in both width and height rather th ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

Discover the step-by-step guide to implementing pagination using NG-ZORRO-Andt in your Angular

I am currently using NG-ZORRO Ant Design pagination on my HTML page and it is displaying correctly in my browser. However, I am struggling with linking the data from the API to the pagination feature. Here is the snippet of my HTML code: <div class ...

A step-by-step guide on incorporating universal CSRF tokens using JQuery AJAX

As part of my development work, I am in the process of creating jquery code that communicates with the server through ajax to input data into a database based on specific request parameters. My main concern at this point is the vulnerability to CSRF attac ...

Modify the height of the panel-header in Bootstrap

I'm attempting to adjust the height of Bootstrap panel-header. However, when I modify the height using the following CSS code: style="height: 20px;" The title inside the header becomes misaligned. To see an example, check out this Plunker demo. Wh ...

Exploring the handling of the nth element within a jQuery each loop

In the process of looping through elements using an each loop, function test(){ $('#first li').each(function(n){$(this).//jQuery effects for nth li of first \\ need to process nth li of id="second" simultaneously }); Is there a wa ...

Guide on implementing dynamic directives, functions, and parameters within AngularJS

I am currently facing a challenge with dynamic rendering in Angular using ngRepeat. I have an object that contains information on which directives to render in the markup and also the values to assign to those directives. Being able to achieve this type of ...

You will still find the information added with JQuery append() even after performing a hard refresh

After making an Ajax call using JQuery and appending the returned information to a div with div.append(), I encountered a strange issue. Despite trying multiple hard refreshes in various browsers, the appended information from the previous call remained vi ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

How to upload multiple files using AngularJS and Laravel without using a form tag

I am seeking a solution to upload multiple files without using the form tag, utilizing AngularJS with Laravel 5.2. The code snippet below is functional for uploading a single file but fails when attempting to upload multiple files. Here is the HTML Code: ...