AngularJS:ng-if检查模型值,但仅当输入为$ valid时输入集的模型值

rod*_*tti 4 javascript angularjs

这是我想做的事情:

  • 我有一个带有两个输入的表单,一个是"email",另一个是"password".
  • 在$ scope中有一个名为form的对象
  • 两个输入都有ng-model指令(ng-model ="form.input_name")
  • 我只想在输入中键入内容时,在输入旁边显示一个图标
  • 该图标附加了一个动作以清除输入(使用angularjs hammer的指令'ng-tap').
  • 要检查输入是否已设置并显示图标,请使用ng-if ="form.input_name.length> 0".
  • 问题是,输入的模型值仅在输入为$ valid时设置,因此对于我的电子邮件输入,只有在输入中键入的内容具有有效的电子邮件格式(a@a.com)时才会显示图标.

有没有办法在ng-if上检查输入的视图值,还是有更好的解决方案来显示图标?

这是我正在使用的代码(省略了css类):

-HTML:

<form name="form-login">
  <input placeholder="email" type="email" ng-model="form.email" required>
  <i hm-tap="clearContent('email')",ng-if="form.email.length>0">

  <input placeholder="password" type="email" ng-model="form.passwd" required>
  <i hm-tap="clearContent('passwd')",ng-if="form.passwd.length>0">
</form>   
Run Code Online (Sandbox Code Playgroud)

- 清除coffeescript输入的功能

$scope.clearContent = (fieldName) ->
      switch fieldName
        when 'passwd' then $scope.form.passwd = ""
        when 'email' then $scope.form.email = "" 
Run Code Online (Sandbox Code Playgroud)

这适用于密码输入(因为它没有验证).谢谢阅读.

The*_*One 11

浏览器验证将使输入的内部值保持为空,直到通过验证.在这种情况下,电子邮件验证.这意味着用户看到的内容和JS看到的内容是不同的!

您可以检查表单输入$viewValue并显示其长度是否大于0.您必须为表单(您已经拥有)和每个输入(我添加的)命名.您也可以访问每个值FORMNAME.INPUTNAME.$viewValue.

<form name="formLogin">
    <input placeholder="email" type="email" name="email" ng-model="form.email" required /> <i hm-tap="form.email = ''" ng-if="formLogin.email.$viewValue.length>0">!</i>
    <input placeholder="password" type="password" name="passwd" ng-model="form.passwd" required /> <i hm-tap="form.passwd = ''" ng-if="formLogin.passwd.$viewValue.length>0">!</i>
</form>
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/TheSharpieOne/6M5JX/1/

此外,您可以clearContent通过直接在[设置空字符串]字段来避免此功能hm-tap