Need ID of SELECT in ngRepeat but get "Syntax Error: Token '{' invalid key at column ## ""

时间:2016-04-04 16:56:02

标签: angularjs ng-messages

I'm using ng-repeat to generate a group of selects. It works, mostly.

Now I'm trying to set up ngMessages to display errors for a custom directive that checks for duplication selections, and set that SELECT to invalid.

However, the ngMessages directive attribute does not like the Form1.Select_{{$index}} syntax. This should parse to Form1.SELECT_0 etc. Note, this sytnax works in the ng-show attribute. How do I get this to work for ngMessages? I need to set ngMessages to the elements $error array.

 <span class="error" style="color:red" ng-show="Form1.Select_{{$index}}.$touched" ng-messages="Form1.Select_{{$index}}.$error" >
       <span ng-message="required">select an option</span>
      <span ng-messages-include='errormessages.html'>  </span>
</span>

1 个答案:

答案 0 :(得分:1)

You can't use interpolation ({{ }}) inside an angular expression (for example, the ng-show or ng-messages attribute value).

Here's a complete example doing what you want:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.5.3" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <form name="form1">
      <div ng-repeat="a in ['a', 'b', 'c'] track by $index">
        <select name="selects_{{ $index }}" ng-model="selections[$index]" required>
          <option value=""></option>
          <option value="1">1</option>
          <option value="2">1</option>
          <option value="3">1</option>
        </select>

        {{ selections[$index] }}

        <span class="error" style="color:red" ng-show="form1['selects_' + $index].$touched" ng-messages="form1['selects_' + $index].$error">
          <span ng-message="required">select an option</span>
        </span>
      </div>
    </form>
  </body>

</html>