Create array dynamically while typing and deleting when the value is empty?

Asked

Viewed 52 times

0

HTML

<div ng-app="app">
    <div ng-controller="testeCtrl">
        <ul ng-repeat="(keyColumn, column) in columns">
            <li>{{ column.name }}
                <div ng-repeat="method in requireMethods">

                    <input type="text" class="form-control" ng-model="column.validation.messages[$index][method]" />
                </div>
            </li>
        </ul>
        <pre>{{ columns | json }}</pre>
    </div>
</div>

Angularjs

var app = angular.module('app',[]);
app.controller('testeCtrl',function($scope){
    var requireMethods = ['required','remote','maxlength']
    $scope.columns = [{
        name: 'teste',
        validation: {
            messages: []
        }
    },
        {
            name: 'teste1',
            validation: {
                messages: []
            }
        },
    ];
    $scope.requireMethods = requireMethods;
});

Join Jsfiddle to understand better: https://jsfiddle.net/vosnwb1s/1/

"name": "teste1",
    "validation": {
    "messages": [
        null,
        null,
        {
            "maxlength": ""
        }
    ]
}

I arrived at this solution, but the array is creating null depending on the place you type in input text. I’d like to know how I exclude the objeto when the value is equal to empty, for example:

{
    "maxlength": "Digitado"
}

When the maxlenght: "", exclude from the object array...

1 answer

0


You can check on change of the input if the property is empty, if yes, instead of using delete, use splice to remove the object from the message array:

// indexPai é referente ao index de colums.
// index é referente ao index de messages
// method para saber se o valor da propriedade esta vazia    
$scope.remover = function(indexPai, index, method){
  if ( ! $scope.columns[indexPai].validation.messages[index][method] )
    $scope.columns[indexPai].validation.messages.splice(index,1);
}

The splice() method changes the contents of a list by adding new ones elements while removing old elements.

Jsfiddle: https://jsfiddle.net/vosnwb1s/3/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.