问题描述
当我尝试从TypeScript使用form.$setPristine
时,它不起作用,并且调试显示form
未定义.根据我阅读的内容,$scope.formName.$setPristine()
会将表格设置为原始格式.为了从控制器访问$scope.formName
,我将其作为ng.IFormController
属性添加到了我的自定义范围接口中.但是,当我调用$scope.form.$setPristine()
时,它不起作用,并且调试显示$scope.form
未定义.
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:
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>
推荐答案
尽管Sobieck00的解决方案也可以工作,但是由于stevuu的建议,我已经对其进行了调试,并找到了一种无需传递表单引用的方法. form
可以作为$scope.$$childTail.form
来访问:
Although Sobieck00's solution works as well, thanks to stevuu's suggestion, I have debugged it and found a way to do it without having to pass the form reference. form
can be accessed as $scope.$$childTail.form
:
interface IMyScope extends ng.IScope {
employees: Array<IEmployee>;
employeeToAdd: IEmployee;
addEmployee(): void;
$$childTail: any; // Add this to access $$childTail in current scope
}
然后在$scope.addEmployee()
中使用以下命令将其重置:
Then in $scope.addEmployee()
reset it with:
$scope.$$childTail.form.$setPristine();
这篇关于带有TypeScript的AngularJS $ setPristine:表单未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!