Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After removing an element from array using splice. its not resetting.Is my code has any mistake

A drop down contains an array value. If i select one value from drop down it will remove that value from array its working. But on click of reset button it should reset with old values .Here is my code

HTML code

<html>
<head>
<script src="angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="exerciseTypeCtrl">
   <select id="exerciseSuperCategory" data-role="listview" ng-options="Lay.id as Lay.value for Lay in Layer " ng-model="itemsuper" ng-change="changeData(itemsuper)">
   </select> 
   <input type="button" ng-click="resetLayer()" value="Reset"/>        

</div>
</body>
</html>

angularjs controler code

<script>
var myApp = angular.module('myApp',[]);

myApp.controller('exerciseTypeCtrl',function($scope)
{

    $scope.Layer = [
        { id: 1, value: '0.38'},
        { id: 2, value: '0.76'},
        { id: 3, value: '1.14'},
        { id: 4, value: '1.52'},
        { id: 5, value: '1.9'},
        { id: 6, value: '2.28'},
        { id: 7, value: '2.66'},
        { id: 8, value: '3.04'},
        { id: 9, value: '3.42'},
        { id: 10, value:'3.8'},
        { id: 11, value: '4.18'},
        { id: 12, value: '4.56'}
    ];

     $scope.changeData = function(value)
      {

         var coating = $scope.Layer;
         if(coating != null)
         {
                var j = coating.length;                                 
                while(j>0)
                {
                    j =j-1;
                    var make = coating[j]['id'];    
                    var present = 0;


                        if(make == value)
                        {                                                           
                          coating.indexOf(make);
                          coating.splice(j,1);                        
                        }

                }
         }
      }
      $scope.resetLayer -function()
      {
          $scope.Layer =  $scope.Layer;
      }

});
</script> 

using splice i am removing the dropdown selected value. but on click of button its not resetting

Thanks in advance

like image 510
user1187 Avatar asked Sep 29 '22 06:09

user1187


1 Answers

You should take a copy of variable while you intialize/get Layer data

var copyOfLayer = angular.copy($scope.Layer);

Then while reseting it you need to do assign old array to the $scope.Layer also you need to rewrite your resetLayer function to below

  $scope.resetLayer = function() {
    $scope.Layer = angular.copy(copyOfLayer)
  }

Working Plunkr

like image 76
Pankaj Parkar Avatar answered Oct 06 '22 02:10

Pankaj Parkar