Created
March 17, 2015 09:50
-
-
Save stefanvangastel/3fd27e9c02fe999dde53 to your computer and use it in GitHub Desktop.
CakePHP 3 form validation message by AngularJS directive
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
var appDirectives = angular.module('appDirectives', []); | |
/** | |
* Add potential validation fields to form-control form elements (CakePHP 3 with Bootstrap) | |
* | |
* Requirement: $scope.errors contains option (validation) errors in default CakePHP 3 JSON response | |
*/ | |
appDirectives.directive('formControl', function($compile) { | |
return { | |
restrict: 'C', //Match all elements with form-control class | |
link: function(scope,element,attrs){ | |
//Get the model and fieldname (name.field) | |
var elements = attrs.ngModel.split("."); | |
//Create a placeholder for error(s) | |
var template = "<span ng-repeat='(type, error) in errors." + elements[1] + "' class='help-block'><p class='text-danger'>{{error}}</p></span>"; | |
//Compile the template and append it to the parent of the form-control element | |
element.parent().append($compile(template)(scope)); | |
} | |
} | |
}); |
Thanks, very useful!
Works like charm, thank you!
Any suggestions how to perhaps make this work well with ng-messages?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expects (validation)errors in a $scope.errors variable.
Example is based on Bootstrap css class, change to whatever works for you.