Last active
April 12, 2016 22:04
-
-
Save heavysixer/1952297874f8bf1ca6eb07e126e3ec8d to your computer and use it in GitHub Desktop.
Angular 1.x directive for displaying rails errors in the view.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
/** | |
* @ngdoc directive | |
* @name hsFormErrors | |
* @module humansized.directives.hsFormErrors | |
* @restrict E | |
* | |
* @description | |
* | |
* A directive that reads errors from a config object and displays them for the viewer. | |
* | |
* @usage | |
* | |
* HAML example: | |
* %hs-form-errors(data-errors="challenge.errors" data-kind='challenge') | |
*/ | |
var hsFormErrors = function () { | |
return { | |
restrict: 'E', | |
template: '' + | |
'<div id="error_explanation" ng-show="errorCount > 0">' + | |
' <h2>{{errorCount}} {{errorMessage}} prohibited this {{ record }} from being saved:</h2>' + | |
' <ul>' + | |
' <li ng-repeat="(key, value) in errors">' + | |
' <span ng-hide="key == \'base\'">{{format(key)}}</span>' + | |
' {{value.join(\' and, \')}}' + | |
' </li>' + | |
' </ul>' + | |
'</div>', | |
scope: { | |
errors: '=', | |
kind: '=' | |
}, | |
controller: ['$scope', function ($scope) { | |
var capitalize = function (str) { | |
return str.charAt(0).toUpperCase() + str.slice(1); | |
}; | |
var humanize = function (str) { | |
return str.split('_').join(' '); | |
}; | |
$scope.format = function (str) { | |
return capitalize(humanize(str)); | |
}; | |
}], | |
link: function ($scope, $element, $attrs) { | |
$scope.record = $attrs.kind || 'record'; | |
var updateErrors = function (errors) { | |
$scope.errors = errors; | |
$scope.errorCount = Object.keys(errors).length; | |
$scope.errorMessage = ($scope.errorCount === 1) ? 'error' : 'errors'; | |
}; | |
var watcher = $scope.$watch('errors', function (newer) { | |
if (angular.isDefined(newer)) { | |
updateErrors(newer); | |
} else { | |
$scope.errorCount = 0; | |
} | |
}); | |
$scope.$on('$destroy', watcher); | |
} | |
}; | |
}; | |
angular.module('humansized.directives') | |
.directive('hsFormErrors', hsFormErrors); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment