gpt4 book ai didi

javascript - 在 Angular 中,如何在 Controller 的 $scope 中获取表单?

转载 作者:行者123 更新时间:2023-11-30 15:51:33 24 4
gpt4 key购买 nike

有这两个文件:

HTML:

<form name="registrationForm" ng-submit="registerUser()">
...
</form>

JS(在 Angular Controller 内):

$scope.registrationForm.confirmPassword.$setValidity("PasswordsMatch", $scope.validation.doPasswordsMatch);

我得到的错误是 Cannot read property 'confirmPassword' of undefined

这让我相信我无法访问 Controller 中的表单 registrationForm。基于此 ( https://docs.angularjs.org/api/ng/type/ngModel.NgModelController ) 我想我应该。

我见过的其他解决方案包括在提交表单时将表单传递给 Controller ​​,但我需要做的(设置自定义验证)需要在此之前发生。

其他解决方案提到通过 ng-controller 将 Controller 添加到表单,但这没有任何改变。

编辑:从上面的网站,有什么原因可以在这里(https://plnkr.co/edit/ZT0G6ajdbescT72qLKSU?p=preview)访问 $scope.myForm,但只能在 $scope.setEmpty 函数内部访问?

最佳答案

我建议为此使用 Controller 本身而不是 $scope 提供程序。这是我在使用 angularjs 时遇到的第一个问题

在你的 Controller 中:

function MyController($scope) {
var vm = this;
vm.registrationForm.confirmPassword.$setValidity("PasswordsMatch", $scope.validation.doPasswordsMatch);
}

在你的表单中:

<form name="vm.registrationForm" ng-submit="registerUser()">
...
</form>

唯一的问题是您需要在路由或 ngInclude 中指定 controllerAs 属性:

ng-include="templates/my-template.html" ng-controller="MyController as vm"

when('/my-route', {
templateUrl: 'templates/my-template.html',
controller: 'MyController as vm'
})

关于javascript - 在 Angular 中,如何在 Controller 的 $scope 中获取表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39234656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com