Search code examples
javascriptangularjsformsng-showng-hide

How to hide form after ng-submit in Angular JS


I have a form on my index that takes the input of a name. Upon submission of the name using ng-submit, I want to hide the form, then show another div which isn't currently hidden below. I have tried adding in a button to the form to set an ng-click and to show on click but cannot get it working (I took the button out) and just have the submit input.

HTML

<form name="add-name" id="add-name" ng-submit="mainCtrl.addName()">
    <input type="text" class="enter-name" placeholder="Enter your name here..." ng-model="mainCtrl.newName.name">
</form>

<!--- this part should be hidden, but should show when form is submitted --->
<div class="steptwo">
    <h4 class="steptwo-text">{{ mainCtrl.newName.name }}</h4>
</div>

Controller

app.controller('mainController', function($scope) {

    this.newName = { name: '' };

    this.names = this.names || [
        { name: ' ' },
    ];

    this.addName = function() {

        this.names.push({
            name: this.newName.name
        });

        this.newName.name = null;
    };
    return this;
});

Any explanation or help would be greatly appreciated.


Solution

  • You can use ng-if or ng-show/hide directive for showing and hiding div depends on expression...

    so first add this directive to part of html you want to show and hide and give them same expression...

    <form name="add-name" id="add-name" ng-submit="mainCtrl.addName()" ng-hide="mainCtrl.hideForm">
        <input type="text" class="enter-name" placeholder="Enter your name here..." ng-model="mainCtrl.newName.name">
    </form>
    
    <!--- this part should be hidden, but should show when form is submitted --->
    <div class="steptwo" ng-show="mainCtrl.hideForm">
        <h4 class="steptwo-text">{{ mainCtrl.newName.name }}</h4>
    </div>
    

    then in your controller just set hideForm variable true so form will be hidden and second step will be shown...

    this.addName = function() {
    
        this.names.push({
            name: this.newName.name
        });
    
        this.newName.name = null;
    
        // hide form
        this.hideForm = true;
    
    };