Skip to content

Instantly share code, notes, and snippets.

@venkatesh22
Last active August 29, 2015 14:24
Show Gist options
  • Save venkatesh22/b9032c27ce9cd64f8faf to your computer and use it in GitHub Desktop.
Save venkatesh22/b9032c27ce9cd64f8faf to your computer and use it in GitHub Desktop.
angular.module('app').controller('Control', function($scope) {
// data from form will go here
$scope.formModel = {};
// field definition here - could also pull from server
$scope.fields = [
{attr: 'firstName', label: 'First Name', required: true, type: 'text', required: true},
{attr: 'lastName', label: 'Last Name', required: true, type: 'text'}
];
})
<form>
<form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
angular.module('app')
.directive('formField', function($compile, $parse) {
return {
restrict: 'E',
compile: function(element, attrs) {
var fieldGetter = $parse(attrs.field);
return function (scope, element, attrs) {
var template, field, id;
field = fieldGetter(scope);
id = 'form-field-' + field.attr; // make a unique string id to match label/input
// ugly, but there's no way around it in angular at the moment
// see Angular author/contributor Misko's answer at
// http://stackoverflow.com/a/10646761
// for an alternate example (though not repeatable as this is)
template = [
'<div class="form-group">',
' <label class="control-label" for="' + id + '">' + field.label + '</label>',
' <input class="form-control" ng-model="' + attrs.ngModel + '" type="' + (field.type || 'text') + '"',
(field.required ? ' required ' : ''),
(field.minLength ? ' ng-minlength="' + field.minLength + '"' : ''),
(field.maxLength ? ' ng-maxlength="' + field.maxLength + '"' : ''),
(field.pattern ? ' ng-pattern="' + field.pattern + '"' : ''),
' id="' + id + '">',
'</div>'
].join('');
element.replaceWith($compile(template)(scope));
}
}
}
})
<!-- the above produces code such as: -->
<form>
<div class="form-group">
<label for="form-field-firstName">First Name</label>
<input class="form-control" ng-model="formModel[firstName]" type="text" required id="form-field-firstName">
</div>
<div class="form-group">
<label for="form-field-lastName">Last Name</label>
<input class="form-control" ng-model="formModel[lastName]" type="text" id="form-field-lastName">
</div>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment