How to clear form with Angularjs?

Asked

Viewed 2,253 times

3

I’m creating an application with Ionic, I have a company registration and after registering the company I want to clean the form but I’m not getting.

How to do this ?

form

<form name="Empresa">
    <div class="list">
        <label class="item item-input" ng-class="{'has-errors':Empresa.nomeemp.$invalid, 'no-errors':Empresa.nomeemp.$valid}">
            <input type="text" placeholder="Nome" name="nomeemp" ng-model="Empresa.nome" ng-required="true">
        </label>
        <div class="error-container" ng-show="(Empresa.nomeemp.$dirty || !Empresa.nomeemp.$pristine)" ng-messages="Empresa.nomeemp.$error">
            <div ng-messages-include="templates/form-errors.html"></div>
        </div>
    </div>
    <button type="button" class="button button-block button-energized" ng-disabled="Empresa.$invalid" ng-click="addEmpresa(Empresa);">Cadastrar</button>
</form>

controller

$scope.addEmpresa = function(Empresa) {
    var _pathFile = document.getElementById("smallimage").src;
    var _fileName = _pathFile.substr(_pathFile.lastIndexOf('/') + 1);
    if(_fileName === 'no-image.png') {
        $ionicLoading.show({ template: APP_MESSAGES.escolhaImagem, noBackdrop: true, duration: 2000 });
    } else {
        $ionicLoading.show();
        EmpresaAPIService.addEmpresa(Empresa).then(function (data) {
            $ionicLoading.hide();
            var retorno = JSON.parse(data.response);
            if(retorno.status === 0){
                $ionicLoading.show({ template: retorno.msg, noBackdrop: true, duration: 2000 });
            }
            if(retorno.status === 1){  
                delete Empresa;
                Empresa.$setPristine();
                Empresa.$setUntouched(); 
                $ionicLoading.show({ template: retorno.msg, noBackdrop: true, duration: 2000 });
            }
        }, function (err) {
            $ionicLoading.hide();
        }, function (progress) {
            // PROGRESS HANDLING GOES HERE
        });
    }
}
  • 1

    Instead of giving deletein the enterprise define an empty object for your company. $scope.form.Empresa = {}

1 answer

3


When I use a form and I need to reset it after use, clean and return to the original state, I use the $Scope.form definition, thus using $Scope.form:

$scope.form = [];


$scope.addEmpresa = function(Empresa){  
//..resto do código
if(retorno.status === 1){  
    delete Empresa;           
    $scope.form.Empresa.$setPristine();
    $scope.form.Empresa.$setUntouched(); 
}
//..resto do código

And on your form, you should also change the name, so:

<form name="form.Empresa">

Browser other questions tagged

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