我只是想知道为什么我必须同时指定 name
和 ng-model
在表单中的输入元素上,以便能够正确使用它。
例如,使用以下内容:
<form name='test'>
<div>
<input type='radio'
value='create-new'
ng-model='toggle'
required />
<input type='radio'
value='use-existing'
ng-model='toggle'
required />
</div>
<div ng-switch='test.$invalid'>
<div ng-switch-when='true'>Invalid!</div>
<div ng-switch-when='false'>Valid!</div>
</div>
</form>
我会得到输出
Invalid!
当我不选择单选按钮时 - 这是正确的行为。但是,缺点是我可以访问此模型的唯一方法是通过 $scope.toggle
- 元素本身不能通过 $scope.test
中的名称引用(表单容器)。 $scope.test
将包含 toggle
的验证规则, 但它不会让您知道这些验证规则属于 toggle
因为名字不存在。如果我们要切换它,请在输入上放置一个名称属性:
<form name='test'>
<div>
<input type='radio'
value='create-new'
name='toggle'
required />
<input type='radio'
value='use-existing'
name='toggle'
required />
</div>
<div ng-switch='test.$invalid'>
<div ng-switch-when='true'>Invalid!</div>
<div ng-switch-when='false'>Valid!</div>
</div>
</form>
然后我们的
ng-switch
底部将始终显示有效,即使我已经提到输入本身是必需的。此外,toggle
现在显示在 $scope.test
内部,所以我可以检查 $scope.test.toggle
的有效性其他地方(不需要该元素的内联属性)。如果我结合这两种方法并同时使用
name
和 ng-model
, 然后合并两个结果,我得到了我预期的结果 - 我可以看到 $scope.test.toggle
并且模型本身正在正确验证。我的问题是为什么这是适当的行为?它似乎与
jquery.validate.unobtrusive
不同。 ,其中 name
属性是本质上将验证规则与元素联系起来的位。
最佳答案
name
属性用于 Angular 验证,ng-model
用于绑定(bind),
如果您不打算使用 Angular 进行验证,则不必使用 name
如果您没有绑定(bind),请不要使用 ng-model
如果您需要在客户端使用 Angular 验证并需要绑定(bind),两者都是必要的
关于angularjs - 为什么我需要在 AngularJS 的输入中同时指定名称和 ng-model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26217392/