StackOverflow_23616578: issue-applying-custom-form-validation-class-in-ng-repeat

Illustration of answer to http://stackoverflow.com/questions/23616578/issue-applying-custom-form-validation-class-in-ng-repeat.

by ExpertSystem

HTML

<script src="http://code.angularjs.org/1.2.16/angular.min.js"></script>
<div ng-controller="myCtrl">
    <table ng-form="myForm">
        <tr ng-repeat="item in items">
            <td>
                <select later-name="itemName{{$index}}" 
                        ng-model="item.name" 
                        ng-options="o for o in item.nameOptions"
                        ng-class="{
                            'custom-error':
                                    myForm.itemName{{$index}}.$invalid &&
                                    !myForm.itemName{{$index}}.$pristine
                        }"
                        required>
                    <option value="">SELECT</option>
                </select>
            </td>
        </tr>
    </table>
</div>

CSS

.custom-error {
    background-color: Red;
}

JavaScript

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.items = [
        {nameOptions: ['Name 1.1', 'Name 1.2', 'Name 1.3']},
        {nameOptions: ['Name 2.1', 'Name 2.2', 'Name 2.3']},
        {nameOptions: ['Name 3.1', 'Name 3.2', 'Name 3.3']}
    ];
});

app.directive('laterName', function () {
    return {
        restrict: 'A',
        require: ['?ngModel', '^?form'],
        link: function postLink(scope, elem, attrs, ctrls) {
            attrs.$set('name', attrs.laterName);

            var modelCtrl = ctrls[0];
            var formCtrl  = ctrls[1];            
            if (modelCtrl && formCtrl) {
                modelCtrl.$name = attrs.name;
                formCtrl.$addControl(modelCtrl);
                scope.$on('$destroy', function () {
                    formCtrl.$removeControl(modelCtrl);
                });
            }            
        }
    };
});