在 Angular 中,如何在控制器的 $scope 中获取表单? [英] In Angular, how to get a form in $scope in controller?

查看:29
本文介绍了在 Angular 中,如何在控制器的 $scope 中获取表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这两个文件:

HTML:

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

JS(在 Angular 控制器内部):

JS (inside the Angular controller):

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

我收到无法读取未定义的属性'confirmPassword'

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

This leads me to believe that I have no access to the form registrationForm in the controller. Based on this (https://docs.angularjs.org/api/ng/type/ngModel.NgModelController) I imagined that I should.

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

Other solutions that I've seen include passing the form to the controller when the form is submitted, but what I need to do (set custom validation) needs to happen way before that.

其他解决方案提到通过 ng-controller 将控制器添加到表单中,但这没有任何改变.

Other solution mentioned adding the controller to the form via ng-controller but that changed nothing.

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

From the website above, is there a reason why in here (https://plnkr.co/edit/ZT0G6ajdbescT72qLKSU?p=preview) $scope.myForm can be accessed, but only inside of the $scope.setEmpty function?

推荐答案

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

I recommend using the controller itself instead of the $scope provider for this. This was one of the first issues I came across when working with angularjs

在您的控制器中:

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

在您的表单中:

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

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

The only gotcha is that you need to specify the controllerAs property in your route or ngInclude:

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

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

这篇关于在 Angular 中,如何在控制器的 $scope 中获取表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆