Search code examples
angularjspushsplice

how to prevent delete and add in all sections - AngularJS


I have a problem when adding several sections and within each section attempt to add other questions, but these are added in all sections. I hope someone can help.

code here: http://goo.gl/XQas0x


Solution

  • Just one questions array is not enough to represent each items section. If you think about it, there must be one array per item. You could make questions a property of each item as NMittal suggests. That will work.

    Another approach, if you want to keep those separated, is to ensure the structure of your questions array matches the items array.

    http://plnkr.co/edit/s7RUfUFcjSnr3L0GajkX?p=preview

    We're using a nested ng-repeat, so we must temporarily store the $index of the items array for use in the ng-repeat for questions.

    <div ng-repeat="item in items" data-sec="@{{$index}}" ng-init="itemIndex=$index">
    

    next use that variable:

    <div class="input-group" ng-repeat="question in questions[itemIndex]" style="margin-bottom: 15px;">
    

    Now the ng-repeats are at least looking in the right place, but it's not enough because Add_Question() and Remove_Question() don't know about this new data structure. Here's how to update them:

    <button ng-click="Add_Question(itemIndex)" class="btn btn-success">Agregar Pregunta</button>
    

    and

    <span class="input-group-addon" style="cursor: pointer;" ng-click="Remove_Question($index, itemIndex)">
    

    and finally the JS side:

    $scope.questions = {};
    
    $scope.Add_Question = function(itemIndex) {
      if($scope.questions[itemIndex] === undefined){
        $scope.questions[itemIndex] = [];
      }
      $scope.questions[itemIndex].push({
    
      });
    };
    
    $scope.Remove_Question = function(index, itemIndex) {
      $scope.questions[itemIndex].splice(index, 1);
    }