Jess McKenzie
Jess McKenzie

Reputation: 8385

Angular JS HTML5 Validation

I have a form that I have used the required tag on my inputs - this works fine but on my submit button I have ng-click="visible = false" that hides the form when the data is submitted.

How could I make it so that its only set to false if all the validation is correct?

App.js

 $scope.newBirthday = function(){

        $scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate});

        $scope.bdayname = '';
        $scope.bdaydate = '';

    };

HTML:

 <form name="birthdayAdd" ng-show="visible" ng-submit="newBirthday()">
        <label>Name:</label>
        <input type="text" ng-model="bdayname" required/>
        <label>Date:</label>
        <input type="date" ng-model="bdaydate" required/>
        <br/>
        <button class="btn" ng-click="visible = false" type="submit">Save</button>
      </form>

Upvotes: 4

Views: 7004

Answers (1)

Ganaraj
Ganaraj

Reputation: 26841

If you give a name to the form that FormController will be exposed in the nearest controller scope by its name. So in your case say you have a structure something like

<div ng-controller="MyController">
    <!-- more stuff here perhaps -->
    <form name="birthdayAdd" ng-show="visible" ng-submit="newBirthday()">
        <label>Name:</label>
        <input type="text" ng-model="bdayname" required/>
        <label>Date:</label>
        <input type="date" ng-model="bdaydate" required/>
        <br/>
        <button class="btn" ng-click="onSave()" type="submit">Save</button>
      </form>
</div>

Now in your controller

function MyController($scope){
    // the form controller is now accessible as $scope.birthdayAdd

    $scope.onSave = function(){
        if($scope.birthdayAdd.$valid){
            $scope.visible = false;
        }
    }
}

If the input elements inside the form are valid then the form will be valid. Hope this helps.

Upvotes: 4

Related Questions