如何使 angular.js 验证在 <form> 标签内工作

How to make angular.js validation work inside a <form> tag

我写了这段代码,但当我将我的应用程序放在 <form name="myForm">... 标签内时它不起作用。我应该怎么做才能让它发挥作用! (每当我将 myForm 放在 ng-app 内时,它就可以工作,但我的应用程序应该在 <form> 内)

<form name="myForm">
    <div ng-app ng-init="myInput = 'ABC'">
        <input name="myInput" ng-model="myInput" required>
        <h1>{{myForm.myInput.$valid}}</h1>
    </div>
</form>

jsfiddle

您在 form 标签内有 ng-app 标签。所以这就是 myFormform 标签不会被 angular 编译并且 myForm 在 angular 范围内不可用的原因。

您应该将 ng-app 移动到最顶层的父级,主要是 html/body 标签,这样您将确保 angular & 编译的所有内容都留在 angular上下文。

<form ng-app name="myForm">
    <div  ng-init="myInput = 'ABC'">
        <input name="myInput" ng-model="myInput" required>
        <h1>{{myForm.myInput.$valid}}</h1>
    </div>
</form>

Forked Fiddle

Its not good idea to create a angular application without modules. Ideally it should have module & provide that module inside ng-app directive. I guess you are learning that's why you had it there.

您可以使用 ngForm 指令(此处)启用其中的验证服务:

像这样:

<div ng-app="" ng-controller="validateCtrl" name="myForm" novalidate ng-form>