AngularJS - Release Scope Directive with Form Submission
I am working on a form input directive.
http://jsfiddle.net/TR9Qt/1/
<form name="form">
<ng-form-field label="Email validation NOT working"></ng-form-field>
<label for="test_email">Test Email with working validation</label>
<input type="email" name="test_email"
ng-model="formData.testEmail" placeholder="Email" required />
<div class="error-message" ng-show="form.test_email.$dirty && form.test_email.$invalid"> <span ng-show="form.test_email.$error.required">Tell us your email.</span>
<span
ng-show="form.test_email.$error.email">This is not a valid email.</span>
</div>
var myApp = angular.module('myApp', []);
myApp.directive('ngFormField', function ($compile) {
var labelTemplate = '<label for="user_email">{{label}}</label>';
var inputTemplate = '<input type="email" name="user_email" ng-model="formData.email" placeholder="Email" required />' +
'<div class="error-message" ng-show="form.user_email.$dirty && form.user_email.$invalid">' +
'<span ng-show="form.user_email.$error.required">Tell us your email.</span>' +
'<span ng-show="form.user_email.$error.email">This is not a valid email.</span>' +
'</div>';
return {
transclude: true,
scope: {
label: '@'
},
// append
replace: true,
// attribute restriction
restrict: 'E',
controller: function ($scope, $element, $attrs) {},
// linking method
link: function ($scope, element, attrs) {
element.html(labelTemplate + inputTemplate);
$compile(element.contents())($scope);
}
}
});
Why not validate the form when I put it in the directive?
Thanks
Tee
+3
source to share
2 answers
I haven't directives yet, but two things popped up at me:
- You don't need to compile your directive if not used in ng-repeat.
-
Your directive has been attached to a label instead of a form field.
<input ng-form-field type="email" name="test_email" ng-model="formData.testEmail" placeholder="Email" required />
+1
source to share
A bit late to the party, but the problem you ran into was that you were using an isolated area when you tried to compile. The isolated area is not directly inherited from the parent, but it is still accessible through $ parent. I solved your problem by simply binding the value of the label attribute to the current scope; it may not be what you want, but it solves your immediate problem.
var myApp = angular.module ('myApp', []); myApp.directive ('ngFormField', function ($ compile) { var labelTemplate = '{{label}}'; var inputTemplate = '' + '' + 'Tell us your email.' + 'This is not a valid email.' + ''; return { // append replace: true, // attribute restriction restrict: 'E', // linking method link: function ($ scope, element, attrs) { $ scope.label = attrs.label; element.html (labelTemplate + inputTemplate); $ compile (element.contents ()) ($ scope); } }; });
work plunker
+1
source to share