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

查看:168
本文介绍了在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);

我收到Cannot read property 'confirmPassword' of undefined

这使我相信我无法访问控制器中的表格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天全站免登陆