Skip to content

Instantly share code, notes, and snippets.

@zacharyvoase
Created June 21, 2016 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacharyvoase/1e50ab8f0c3817eb26b439d2e1753d75 to your computer and use it in GitHub Desktop.
Save zacharyvoase/1e50ab8f0c3817eb26b439d2e1753d75 to your computer and use it in GitHub Desktop.
Sync form field validation state between Angular and Bootstrap
/**
* Angular's ngModel helpfully adds the `ng-invalid` class to form controls
* containing invalid input. However, Bootstrap forms are typically structured
* like so:
*
* <div class="form-group">
* <label>Name*</label>
* <input class="form-control" type="text" ng-model="user.name" />
* </div>
*
* When a field contains an invalid value, you normally add a `has-error` class
* to the parent `form-group`. These two directive definitions help sync that
* validation state between the Angular way of doing things and the Bootstrap
* world.
*
* All elements matching `.form-group` get a controller instance with a method
* for toggling the `has-error` class. `.form-control` elements having
* an `ng-model` will synchronize their `.$valid` state either with that parent
* `.form-group`, or just on the element itself if the form control is not
* contained by a group.
*/
app.directive('formGroup', function() {
return {
restrict: 'C',
controller: function () {},
link: function (scope, elem, attrs, controller) {
controller.setValidity = function(isValid) {
elem.toggleClass('has-error', !isValid)
}
}
};
})
app.directive('formControl', function() {
return {
restrict: 'C',
require: ['?ngModel', '?^formGroup'],
link: function(scope, elem, attrs, controllers) {
var modelCtrl = controllers[0],
groupCtrl = controllers[1];
if (!angular.isDefined(modelCtrl)) {
return;
}
var validityChanged
if (groupCtrl != null) {
validityChanged = function(isValid) { groupCtrl.setValidity(isValid) }
} else {
validityChanged = function(isValid) { elem.toggleClass('has-error', !isValid) }
}
modelCtrl.$viewChangeListeners.push(function() { validityChanged(modelCtrl.$valid); });
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment