Search code examples
angularjsnested-listscustom-lists

Arrange lists of lists on button click Angularjs


I have data, two input fields with a button and on clicking the button I want to move the data to certain position:

i.e two input fields = source and destination it's basically the indexes to move a certain item from source to destination

data=

        {
      "0": [
        {
          "key": "Survey Meta Data"
        }
      ],
      "1": [
        {
          "key": "New Section"
        }
      ],
      "2": [
        {
          "key": "Tax Authority"
        }
      ]
    }

explaining what I want the input field source=2destination=0 now my data will be

    {
  "0": [
    {
      "key": "Tax Authority"
    }
  ],
  "1": [
    {
      "key": "Survey Meta Data"
    }
  ],
  "2": [
    {
      "key": "New Section"
    }
  ]
}

As it's moved to the first index and other items are pushed any help will be greatly appreciated

index.html

Source=<input  ng-model="source" type="number>
Destination<input ng-model="destination" type="number>
<button ng-click="arrange(source,destination)></button>
{{model|json}}

index.js

$scope.model=[[{"key":'Survey Meta data'}],[{key:'New Section'}],[{key:Tax Authority'}]]

$scope.arrange(src,dest)
{
//trick to push
}

Solution

  • You just have to use splice to achieve this.

    JS:

       $scope.myObj = {
        "0": [{
            "key": "Survey Meta Data"
        }],
        "1": [{
            key: 'New Section'
        }],
        "2": [{
            "key": "Tax Authority"
        }]
    };
    $scope.model = [];
    for (var i in $scope.myObj) {
        if ($scope.myObj.hasOwnProperty(i)) {
            $scope.model.push($scope.myObj[i]);
        }
    }
    Array.prototype.insert = function(index, item) {
        this.splice(index, 0, item);
    };
    $scope.arrange = function(src, dest) {
        var temp = [];
        temp = $scope.model.splice(parseInt(src), 1);
        $scope.model.insert(parseInt(dest), temp[0]);
        for (var i = 0; i < $scope.model.length; i++) {
            $scope.myObj[i] = $scope.model[i];
        }
    }
    

    Demo: http://jsfiddle.net/yj9sswq1/5/