JSFiddle - React, Tailwind, and code Playground
by chrish
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<div ng-app="myApp">
<h2>Form Directive Test</h2>
<div ng-controller="TestCtrl">
<form name="testForm" novalidate>
<div ng-class='{ "error": testForm.field1.$invalid }'>
<label>Field1</label>
<input name="field1" type="text" ng-model="field1" />
</div>
<form-text-field iw-model="field2" iw-form-name="testForm" iw-field-name="field2" iw-label="Field2"></form-text-field>
<input name="submit" type="submit" ng-click="submit()"></input>
</form>
</div>
</div>
CSS
.error input {
border: 1px solid red;
}
JavaScript
var myApp = angular.module('myApp',[]);
function TestCtrl($scope) {
$scope.field1 = "field1";
$scope.field2 = "field2";
$scope.submit = function() {
console.log("Field1:" + $scope.testForm.field1);
console.log("Field2:" + $scope.testForm.field2);
$scope.testForm.field1.$setValidity('test', false);
$scope.testForm.field2.$setValidity('test', false);
};
}
var template = '\
<div>\
<label></label>\
<input type="text" />\
</div>\
';
myApp.directive('formTextField', ['$compile', function ($compile) {
return {
replace: true,
restrict: 'E',
scope: false,
compile: function compile(tElement, tAttrs, transclude) {
var elem = $(template);
var formName = tAttrs.iwFormName;
var fieldName = tAttrs.iwFieldName;
var label = tAttrs.iwLabel;
var model = tAttrs.iwModel;
elem.attr('ng-class', '{ \'error\': ' + formName + '[\'' + fieldName + '\'].$invalid }');
elem.find('label').attr('for', formName + '-' + fieldName);
elem.find('label').html(label);
elem.find('input').attr('id', formName + '-' + fieldName);
elem.find('input').attr('name', fieldName);
elem.find('input').attr('ng-model', model);
// This one is required so that angular adds the input to the controllers form scope variable
tElement.replaceWith(elem);
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
// This one is required for ng-class to apply correctly
elem.replaceWith($compile(elem)(scope));
}
};
}
};
}])
;