$ scope.formName.fieldName。$ setValidity不起作用

时间:2014-08-09 07:05:09

标签: angularjs angularjs-directive

当firstname等于lastname时,我想用angular设置无效,并使用样式将颜色更改为红色。

http://jsbin.com/japir/2

function RegoController($scope) {
  $scope.app = {
    firstName: "Saroj"
  };

  $scope.$watch("app.lastName", function(newVal, oldVal) {
    if (!!$scope.app.lastName && !!newVal)
      if (angular.lowercase($scope.app.firstName) === angular.lowercase(newVal)) {
        debugger;
        $scope.form.inputLastName.$setValidity("sameName", false);
      }

  });
}

<body ng-app>
  <div class="container" ng-controller="RegoController">
    <div class="col-lg-4">
      <form name="form">
        <div class="form-group">
          <label for="inputFirstName">First Name</label>
          <input id="inputFirstName" class="form-control" type="text" ng-model="app.firstName" placeholder="Enter your firstname" required ng-minlength="3" ng-maxlength="20" />
        </div>
        <div class="form-group">
          <label for="inputLastName">Last Name</label>
          <input id="inputLastName" class="form-control" type="text" ng-model="app.lastName" placeholder="Enter your last name" required ng-minlength="3" ng-maxlength="20" />
        </div>
        <div class="form-group">
          <label for="inputEmail">Email</label>
          <input id="inputEmail" class="form-control" type="email" ng-model="app.email" placeholder="Enter your email" required />
        </div>
        <div class="form-group">
          <input type="submit" class="btn btn-primary" value="Save" />
        </div>
      </form>
      {{app}}
    </div>
  </div>
</body>

2 个答案:

答案 0 :(得分:3)

问题是您正在尝试选择没有名称的表单输入;从而使它无法找到您试图使其无效的字段。这是一个有效的例子:

JSBIN:http://jsbin.com/yozanado/1/

输入字段名称为

<input id="inputLastName" name="lastName" class="form-control" type="text" ng-model="app.lastName" placeholder="Enter your last name" required ng-minlength="3" ng-maxlength="20" />

<强>使用Javascript:

$scope.form.lastName.$setValidity("sameName", false);

答案 1 :(得分:1)

AngularJS表单验证依赖于表单名称和字段名称来查找范围内的验证模型。

例如,如果您的HTML是:

<form name="form">
     <input name="firstName" ng-model="firstName" />
</form>

您将能够使用名称属性访问作用域上的验证$ error属性:

$scope.form.firstName.$error.sameName

要解决您遇到的问题,请在输入字段中添加名称属性。

JSBin Demo