1

I updated AngularJs version from 1.3 to 1.4. It causes an error as,

Syntax Error: Token '{' invalid key at column 2 of the expression
[{{frmname}}.emailAddress.$error] starting at [{frmname}}.emailAddress.$error].

It works perfectly in Angular 1.3

<form name="{{frmname}}">
  <h1>My form name = {{frmname}}</h1>
  <div class="field">
  <label for="emailAddress">Enter your email address:</label>
  <input type="email" name="emailAddress" ng-model="email" required />
    <div ng-messages="{{frmname}}.emailAddress.$error">
      <div ng-message="required">
        You forgot to enter your email address...
      </div>
      <div ng-message="email">
        You did not enter your email address correctly...
      </div>
    </div>
  </div>
  <input type="submit" />
</form>

FIDDLE

4

2 回答 2

2

如果您需要从动态变量中设置表单名称,那么您可以使用它ng-form来验证实际表单中的输入。

基本的html:

<form name="{{formName}}" novalidate>

  <ng-form name="emailError">
    <div ng-messages="emailError.emailAddress.$error" style="color:maroon" role="alert">
      <label for="emailAddress">Enter your email address:</label>
      <input type="email" name="emailAddress" ng-model="email" minlength="5" required />
      <div ng-messages="emailError.emailAddress.$error" style="color:maroon" role="alert">
      <div ng-message="required">You did not enter a field</div>
    </div>
  </ng-form>

  <input type="submit" />

</form>

Plunker:https ://plnkr.co/edit/Q0ifmRXKkLfwKGNqv8p4?p=preview

ngForm官方文档:https ://docs.angularjs.org/api/ng/directive/ngForm

于 2016-05-17T11:32:06.583 回答
-1

最后我得到了解决方案,

添加获取 ng-messages 属性值的函数。

<div ng-messages="getMessages('emailAddress')">
  <div ng-message="required">
    You forgot to enter your email address...
  </div>
  <div ng-message="email">
    You did not enter your email address correctly...
  </div>
</div>

在控制器或指令中声明函数。

$scope.getMessages = function (el) {
  return $scope.$eval($scope.frmname)[el].$error;
}

小提琴

于 2016-05-17T11:49:24.843 回答