Angularjs在指令内获得表单字段有效性

Gre*_*ith 22 angularjs

我希望这不是重复 - 有很多类似的问题,但我找不到有效的答案.

我有一个Angular指令,因此:

app.directive('emailInput', function(){
    return {
        restrict: 'E',
        templateUrl: 'template.html',
        link: function(scope, elem, attrs, ctrl){
            elem.bind('keyup', function(){
                // TODO - what?
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在模板html中:

<input type="email" required ng-model="emailAddress" />
Run Code Online (Sandbox Code Playgroud)

在不知道表单名称的情况下,在link函数内部,我想知道emailAddress.$valid属性的值- 我怎样才能得到它?

Ada*_*dam 32

您可以使用formController,它可以访问注册到表单的所有输入

app.directive('emailInput', function(){
  return {
      require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM.
      restrict: 'E',
      templateUrl: 'template.html',
      link: function(scope, elem, attrs, ctrl){
          elem.bind('keyup', function(){
              ctrl.emailAddress.$valid //check validity
          })
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

请记住,Angular按名称跟踪输入元素.所以你必须给你的输入一个名字属性

<input type="email" required ng-model="emailAddress" name="emailAddress" />
Run Code Online (Sandbox Code Playgroud)

我还建议可能只是通过指令属性传递所有这些.您可能不想对字段名称进行硬编码.所以你可以拥有一个有效的属性

inputIsValid='formName.emailAddress.$valid'
Run Code Online (Sandbox Code Playgroud)

并在您的指令中评估(或$ watch it).