Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $setPristine with TypeScript: form is undefined

When I try to use form.$setPristine from TypeScript, it doesn't work and the debug says form is undefined. According to what I read, $scope.formName.$setPristine() shall set the form to pristine. To access $scope.formName from the controller, I added it to my custom scope interface as an ng.IFormController property. However, when I call $scope.form.$setPristine(), it doesn't work, and debug shows $scope.form is undefined.

TypeScript:

interface IMyScope extends ng.IScope {
    employees: Array<IEmployee>;
    employeeToAdd: IEmployee;
    addEmployee(): void;
    form: ng.IFormController;
}

class EmployeeAddController {
    static $inject = ['$scope', 'Employees'];

    constructor(
        $scope: IMyScope,
        $modalInstance: ng.ui.bootstrap.IModalServiceInstance,  
        Employees: IUpdateableResourceClass<IUpdateableResource>
    ) {
        $scope.employees = new Array<IEmployee>();

        $scope.employeeToAdd = {
            Name: '',
            Email: ''
        };

        $scope.addEmployee = function () {
            Employees.save(null, $scope.employeeToAdd, function (employee: IEmployee) {
                $scope.employees.push(employee);
                $scope.employeeToAdd.Email = '';
            $scope.employeeToAdd.Name = '';
                $scope.form.$setPristine(); // $scope.form is undefined
            });
        };
    }
} 

HTML:

<form role="form" class="form-inline" name="form">
    <div class="form-group" ng-class="{ 'has-error': form.name.$dirty && form.name.$invalid }">
        <input type="text" class="form-control" ng-model="employeeToAdd.Name" name="name" required>
    </div>
    <div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$invalid }">
        <input type="email" class="form-control" ng-model="employeeToAdd.Email" name="email" required>
    </div>
    <button type="button" class="btn btn-default" ng-click="addEmployee()" ng-disabled="form.$invalid">Add</button>
</form>
like image 644
Adam Szabo Avatar asked Mar 12 '26 09:03

Adam Szabo


1 Answers

What I have done in my application with form is to pass the form object into the method that clears it instead of working off the scope directly.

<button data-ng-click="clearAndResetForm(Form)"></button>

$scope.clearAndResetForm = (form:ng.IFormController)=> {
   this.clearAndResetForm(form);
};


private clearAndResetForm(form:ng.IFormController) {
   this.$scope.fieldOne = undefined;
   this.$scope.fieldTwo = undefined;
   form.$setPristine();
}

I'm not entirely sure why my code would work while yours doesn't. But hopefully this approach might help you.