Use expressions to build variable names in Angular.js

When working with HTML and JavaScript you sometimes have to do weird things to achieve a specific purpose. In my case one of these things was building a variable name with Angular expressions.

While generating a form via ng-repeat, I also had to generate the name of the inputelement.For verification, I wanted to add a CSS class to the input whenever it gets marked as invalid. To access it, I had to usethe form.elementpatternwherefore I wrote something like this, trying to generate the variable name with an expression.


<code class="language-markup"><form name="userForm">
    <div ng-repeat="field in allFields">
        <input id="{{ fieldValue.Name }}" ng-class="{ 'has-error' : userForm{{ fieldValue.Name }}.$invalid }"></input>

The code above does not only cause errors, it also is invalid HTML so I had to find another way. The solution is replacing the double curly braces with simple square brackets so that the final code looked like this:



This works perfectly and is also valid HTML code. I hope that helps and spares your nerves. If you are looking for another working example, you can take a look at this JSFiddle repository, where I created a tiny demo project to play around with.