Simran Kaur
Simran Kaur

Reputation: 1101

posting data through angular form without page reload in angular

$scope.createPermission= function(form){
    AppFactory.createNewPermission(form)
        .success(function(data) { 

            $scope.updatedPermissions = data;

            $scope.navMode='getPermission'

            var original = $scope.permission;
            $scope.reset(original);
            $scope.permission = {}; // clear the form 
        })
        .error(function(data) {
            console.log('Error in creating permission: ' + data);
        });

    $scope.Execute=function(id) {
        if($scope.navMode=='updatePermission') {
            $scope.editPermission(id);
        } else if($scope.navMode=='createPermission') {
            $scope.createPermission($scope.permission);
        }
    }
}

$scope.reset= function(original) {
    $scope.permission= angular.copy(original)
    $scope.form2.$setPristine(true);
    //$scope.form2.$setUntouched(true);
}

HTML:

<div class="row">
    <div class="container col-sm-6 col-sm-offset-2" 
         ng-show="navMode == 'createPermission' || navMode=='updatePermission' || navMode=='getPermission'">

        <div>
            <h1>Permissions</h1>
        </div>
    </div>
    <form class="form2" ng-show="showHide('Create')" ng-if=""name="form2" ng-submit="Execute(permissionId)" novalidate>

        <div class="form-group" ng-class="{ 'has-success': form2.name.$valid && submitted, 'has-error': form2.name.$invalid && submitted }">
            <label>Permission Name</label>

            <input type="text" name="name" class="form-control" ng-model="permission.name" required/>
            <p class="help-block" ng-show="form2.name.$error.required && submitted">
                A permission name is required
            </p>
        </div>

        <div class="row col-lg-offset-3">
            <button class="btn btn-primary" ng-disabled="form2.$invalid" type="submit">Save</button>
        </div>
    </form>
</div>

I have above piece of code in controller and is executed on submission of the form. Now , It does work fine on page reload but I can not add data through form back to back. I need to reload teh page everytime to post new data through the form.

Why exactly is that ?

How do I fix this?

Upvotes: 0

Views: 2435

Answers (1)

rom99
rom99

Reputation: 799

Without seeing the HTML part of this, I would guess you are using the action attribute of <form>. AngularJS provides ng-submit which allows you to set a handler for the submit event, without actually 'submitting' the form in the traditional sense. See https://docs.angularjs.org/api/ng/directive/ngSubmit.

Upvotes: 2

Related Questions