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

Utilizing Bootstrap 5: Breaking a Page into Two Separate Vertical Sections

I am looking to design a unique grid system that divides the page into either 2 columns or 2 rows that are completely separate from each other. This means that the content on one side of the page does not expand to match the height of the content on the ot ...

Having trouble with the installation of [email protected] on Windows 10 x64?

I am currently in the process of setting up hiredis on my Windows 64-bit operating system as it is a requirement for the node-celery package. My system specifications are as follows: Node v7.9.0 npm v4.5.0 Visual Studio Community 2013 with Update 5 (en_ ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Patience is key while waiting for Meteor.loggingIn() to be false

I need help implementing authentication on a React route using Meteor and React.js. Here is my current approach: <Router history={browserHistory}> <Route path="/vendor/chat" component={VendorChat} onEnter={requireVendorAuth} /> </Route ...

Attempting to locate the element's position using Selenium in Python

quem_esta_sacando = driver.find_elements_by_xpath("//div[@class='gameinfo-container tennis-container']/div[@class='team-names']/div[@class='team-name']") this is how I located the correct class, but now I want to ...

Changing innerHTML in CoffeeScript

Are there other options instead of using the 'innerHTML' property in CoffeeScript? In JavaScript, you typically write something like this: document.getElementById('element').innerHTML = "blah_blah" Is there a different approach to ac ...

Practice window.performance.getEntriesByType with a mock function

I am facing an issue in my component where I need to check if the page is reloaded and redirect to another page. Here is the code snippet I am using: useEffect(() => { //this will prevent users from accidentally refreshing / closing tab window.o ...

Looking for tips on resolving issues with the bootstrap navigation bar?

Check out this code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport ...

The attempt to access a Spring Boot webservice using AngularJS and the GET method resulted in a 500 status error, indicating that the operation

I have successfully developed a webservice using springboot and angularjs to download an excel file from the server to my local machine. The URL is being generated correctly, however, I am encountering a 500 error. Below is the code snippet: My Springboot ...

Image link in HTML / CSS not functional on one half of the image

My webpage has an image thumbnail with accompanying text positioned to the right. I have a hyperlink on the image that should open the full-size version when clicked. However, there seems to be an issue where the hyper link only activates on the lower hal ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

"Explore the functionalities of Drupal's innovative Menu module: How sub-sub menus can take precedence over sub-menus

When visiting , I noticed that the Nice Menu module for Drupal is not displaying sub-sub menus properly. If you navigate to the first item in the menu and then select the first one in the sub-menu (Facilities->Spring->Calendar), you'll see that ...

Tips for addressing the issue of mat-list-item not occupying the entire row's space

Hello everyone, I am currently trying to render an article.component.html within my article-list-component.html in a list format. When I use plain HTML, it renders correctly as shown in picture 1: Title - author - Date Here is the code for my article-list. ...

Adjust camera to align with the loaded object in Three.js

I've been struggling to center the camera around the model loaded through the stl loader. I've tried adjusting variables and setting different positions for the mesh and camera, but the camera still isn't centered on the design! Here's ...

Implementing a Slide animation in React

I am currently working on a carousel feature that includes two buttons, Next and Previous. When the user clicks on Next, I want the carousel to slide from left to right, and when they click on Previous, it should slide from right to left. One important not ...

Determine whether the child element extends beyond the boundaries of the parent element

I am currently working on determining whether a child element is visible within its parent element. To achieve this, I am comparing the width of the parent element to the position of the child element using position().left. Given that I have multiple dist ...

Expand the spectrum of the input range

Is there a way to make the cursor and bar of a range input bigger without changing their length? <input id="speed" type="range" min="10" max="80" /> Any suggestions on how to achieve this? Appreciate your assistance. ...

Dealing with the element not present error in Protractor can be managed by using various

Is there a way to achieve similar Exception handling in Protractor as we can with Selenium webdriver in Java? When dealing with element not found exceptions, what is the most effective approach to handle them using Protractor? ...

Specialized selection option with disabled function

Looking for assistance with a script to create a custom select box. I have UL and LI elements overlapping a select element, but I want to prevent the UL LI from opening when the select has a "disabled" attribute. Can anyone provide guidance on how to achie ...