Based on a response script to this question: Dynamic table with angle
Where it creates a PivotTable with angular, but it can not delete the right "cell", it always deletes the last included question. To reproduce the error, just mark the first radio button
of the first column and try to delete the question, it will remain and delete the one from the right column.
var app = angular.module("app", []);
app.filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i = 0; i < total; i++) {
input.push(i);
}
return input;
};
});
app.controller("ctrl", ["$scope", function($scope) {
// criando variavel de perguntas
$scope.answer = ["Sim", "Não"];
// criando variavel de questão
$scope.question = [{
'name': "P 1",
'r': [false, false]
},
{
'name': "P 2",
'r': [false, false]
}
];
// adicionando pergunta
$scope.addAnswer = function() {
$scope.answer.push("R" + (new Date().getTime()));
for (i = 0; i < $scope.question.length; i++) {
$scope.question[i].r.push('false');
}
};
// excluindo pergunta
$scope.delAnswer = function(index) {
$scope.answer.splice(index, 1);
for (i = 0; i < $scope.question.length; i++) {
$scope.question[i].r.splice(index - 1, 1);
}
};
// adicionando questão
$scope.addQuestion = function() {
$r = $scope.answer.map(function() {
return false;
});
$scope.question.push({
'name': 'P' + (new Date().getTime()),
'r': $r
});
};
// excluindo questão
$scope.delQuestion = function(index){
$scope.question.splice(index, 1);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div>
<table border="0">
<tr>
<td>Perguntas:</td>
<td ng-repeat="a in answer">
<input value="{{a}}" style="width:40px" />
<button ng-click="delAnswer($index)"> - </button>
</td>
<td><button type="button" ng-click="addAnswer()"> + </button></td>
</tr>
<tr ng-repeat="q in question">
<td><input value="{{q.name}}" /></td>
<td ng-repeat="b in q.r track by $index">
<input type="radio" name="{{q.name}}" />
</td>
<td><button ng-click="delQuestion($index)"> - </button>
</tr>
<tr>
<td>
<button ng-click="addQuestion()"> + </button>
</td>
<tr>
</table>
</div>
</div>
NOTE: I think the error is in the delAnswer
function, but I can not find the error.