无法获取有效形式 [英] Unable to get form validity

查看:111
本文介绍了无法获取有效形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用$ scope.myform拿到形式有效性$有效和放大器。我得到一个不确定的消息无法读取属性未定义'$有效'。

I'm unable to get form validity using $scope.myform.$valid & I get a undefined message "Cannot read property '$valid' of undefined".

<body ng-controller="MainCtrl">
  <form name="myform">
    Name: <input type="text" ng-model="user.name" /><br>
    Email: <input type="email" ng-model="user.email" /><br>
 </form>
</body> 

app.controller('MainCtrl', function($scope) {
  console.log($scope.myform.$valid);  
});

Plnkr: http://plnkr.co/edit/P2kg1l64d4t7k7X4d4jh?p=preVIEW

推荐答案

这是因为,当你的控制器实例化并执行此行code,表单还没有被添加到的范围呢。

That's because, when your controller is instanciated and this line of code is executed, the form has not been added to the scope yet.

这个功能添加到您的控制器来代替:

Add this function to your controller instead:

$scope.click = function() {
    alert($scope.myform.$valid);
};

和添加到您的形式:

 <button type="button" ng-click="click()">is form valid?</button>

,你会看到,点击按钮时,你就可以拿到表格的有效性的。

and you'll see that, when clicking the button, you'll be able to get the validity of the form.

下面是更新后的 plunker

这篇关于无法获取有效形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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