Angular: Dynamic Field name in Directive Template get input validation

http://angularjs.org/

by Sruti C

HTML

<script src="https://code.angularjs.org/1.2.15/angular.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-controller="MyCtrl">

    <form name="myForm">
        <form-field content="field" model="output[field.uniqueId]" ng-repeat="field in formFields"></form-field>
        </form>                   
</div>

<pre>
myForm.your_name_0.$valid = {{ myForm.your_name_0.$valid }}
    <br/>
myForm.description_1.$valid = {{ myForm.description_1.$valid }}
    <br/>
</pre>

JavaScript

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.formFields = [
        {
        "fieldName": "Your Name",
        "uniqueId": "your_name_0",
        "fieldType": "text",
        "isMandatory": true
        },
        {
        "fieldName": "Description",
        "uniqueId": "description_1",
        "fieldType": "textarea",
        "isMandatory": true,
        }
    ];
    
    $scope.output={};
}

myApp.directive("formField",function($compile){
    var templates = {
        textTemplate:'<div class="form-group"><label for="{{content.uniqueId}}" >{{content.fieldName}}</label> <span ng-show="content.isMandatory" class="sub_reqText">*</span><span ng-show="form.content.fieldName.$invalid">Please check this field.</span><input type="text" ng-model="model" name="{{content.uniqueId}}" class="form-control" ng-required="content.isMandatory" id="{{content.uniqueId}}"/> </div><br>',
        textareaTemplate:'<div class="form-group"><label for="{{content.uniqueId}}" >{{content.fieldName}}</label> <span ng-show="content.isMandatory" class="sub_reqText">*</span> <span ng-show="form.content.fieldName.$invalid">Please check this field.</span> <textarea ng-model="model" name="{{content.uniqueId}}" id="{{content.uniqueId}}"  class="form-control" ng-required="content.isMandatory"></textarea> </div>' 
    };
    
    var getTemplate = function(content, attrs){
        var template = {};
        template = templates[content.fieldType+"Template"];
        if(typeof template != 'undefined' && template != null) {
				return template;
			}
			else {
				return '';
			}
    };
    
    
    var linker = function(scope, element, attrs){        
        element.html(getTemplate(scope.content, attrs)).show();        
        $compile(element.contents())(scope);
    }
    
    return {
        restrict:"E",        
        replace:true,        
        link:linker,
        scope:{
            content:'=',
            model:'=?'
        }
    };
});