当我尝试使用 TypeScript 中的 form.$setPristine 时,它​​不起作用并且调试显示 form 未定义。根据我阅读的内容,$scope.formName.$setPristine() 应将表单设置为原始状态。为了从 Controller 访问 $scope.formName,我将它作为 ng.IFormController 属性添加到我的自定义范围接口(interface)中。但是,当我调用 $scope.form.$setPristine() 时,它​​不起作用,并且调试显示 $scope.form 未定义。

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>

最佳答案

我在我的表单应用程序中所做的是将表单对象传递给清除它的方法,而不是直接处理范围。

<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();
}

我不完全确定为什么我的代码可以工作而你的代码不行。但希望这种方法可以帮助你。

关于AngularJS $setPristine 和 TypeScript : form is undefined,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23322690/

10-10 00:42