Reputation: 896
This is what I am planning to do:
Initial Markup:
<div class="col-md-3 col-sm-3 col-xs-6">
<span class="control-label"><b>Doc. Number:</b></span>
<input name="documentNumber" class="form-control" type="text" ng-model="document.number" smrh-required />
</div>
Attempted Markup with my directive:
<div class="col-md-3 col-sm-3 col-xs-6" ng-class="{'has-error': t01Form.documentNumber.$invalid && t01Form.documentNumber.$dirty}">
<span class="control-label"><b>Doc. Number:</b></span>
<input name="documentNumber" class="form-control " type="text" ng-model="document.number" smrh-required="" required="" />
<p ng-show="t01Form.documentNumber.$invalid && t01Form.documentNumber.$dirty" class="help-block">Document Number is required.</p>
</div>
Below is the custom directive I have created to attempt this:
app.directive('smrhRequired', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attributes, controller) {
element.attr('ng-required', "");
//This way it will only show the red outline if the error happens.
var errorClass = " {'has-error': " + scope.formName + "." + element[0].name + ".$valid && " + scope.formName + "." + element[0].name + ".$dirty }";
var currentNgClass = element.parent().attr('ng-class');
if (currentNgClass != null) {
element.parent().attr('ng-class', currentNgClass + errorClass);
} else {
element.parent().attr('ng-class', errorClass);
}
//Adding the error message below the input
var template = '<p ng-show="' + scope.formName + '.' + element[0].name + '.$invalid && ' + scope.formName + '.' + element[0].name + '.$dirty" class="help-block">' + ' is required.' + '</p>';
element.parent().append(template);
$compile(element.contents())(scope);
},
};
});
Now the above functions adds the new markup correctly, but none of the new markup works. Even though I added the required attribute dynamically.. the control still show $valid.
The new
I added shows up regardless of the ng-show logic.
I am guessing it is because I am adding elements to DOM after angular has already compiled, but I thought that's what $compile is for?
Upvotes: 0
Views: 94