Directive input element name (formController)

Setting the name on an input element so that can show validation errors.

by programmieraffe

HTML

<script src="http://ci.angularjs.org/job/angular.js-angular-master/ws/build/angular.min.js"></script>
<p>Testing Setting of the name on an element</p>
<hr/>
<div ng-app="interfaceSettings">
    
    Angular: 1.0.0rc6
    
    <h2>Directive w/o ng:include</h2>
    <div ng-controller="TestDirective">
    <my:input name="title" label="Titel" ns="form"></my:input>
    </div>
    <h2>Directive inside ng:include</h2>
<div ng-controller="TestDirective">
    <ng:include src="'template.html'"></ng:include>
</div>
        <h2>Directive inside ng:include with div-wrapping</h2>
<div ng-controller="TestDirective">
    <ng:include src="'template-working.html'"></ng:include>
</div>
</div>

CSS

body {
    padding: 10px; 
    font-family: sans-serif; 
    font-size: 0.9em;
}
form label {font-weight:bold;margin-right:10px;font-size:0.9em;}
form label:after {content:':';}
input.ng-invalid, select.ng-invalid, textarea.ng-invalid, input.formElement.ng-invalid {
    border: solid 1pt red;
}
div.formEntry {
    margin-bottom:5px;padding-bottom:10px;border-bottom:solid 1px #eee;   
}

JavaScript

var settingsModule = angular.module('interfaceSettings', []);
settingsModule.directive('myInput', function() {
    return {
        restrict: 'E',
        // only elements
        compile: function(element, attrs) {

            var name = attrs.name;
            var label = attrs.label || name;
            var ns = attrs.ns || 'form'; //the namespace to use
            var ngvalidate = attrs.ngValidate || '';

            element.replaceWith('<div class="form_field">' + '<label for="' + ns + '.' + name + '">' + label + ':</label>' + '<input type="text" name="' + name + '" ng-model="' + ns + '.' + name + '" ng:validate="' + ngvalidate + '" />' + '<span class="form_error" ng:show="errors.' + ns + '.' + name + '">{{errors.' + ns + '.' + name + '}}</span>' + '</div>');
        }
    }
});

function TestDirective($scope,$templateCache) {

    $templateCache
    $templateCache.put('template.html', '<my:input name="title" label="Titel" ns="form"></my:input>');
    
    $templateCache.put('template-working.html','<div><my:input name="title" label="Titel" ns="form"></my:input></div>');
    
    $scope.settings = {
        angularVersion: angular.version
    };

    $scope.errors = {}; // error container for controller
    $scope.errors.form = {};
    
    // sample error - is generated by a validator
    $scope.errors.form.title = 'Error - title already exists';

}