I am new to angular and maybe trying to do the wrong thing.
What I am trying to, is to create a validation message directive, which can show validation message for a specific input field in a form. It should only show the validation message for required fields in case the input field is missing a value.
I've tried with the following HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<form name="myForm">
<input name="myInput" type="text" x-ng-model="object.input" required/><br/>
<span ng-show="myForm.myInput.$error.required" >Value required (working)</span><br/>
<span x-msg-required="myForm.myInput"></span>
</form>
</body>
</html>
and the JS:
var app = angular.module('myApp', []);
app.directive('msgRequired', function() {
return {
link : function(scope, element, attrs) {
element.text('Value required');
attrs.$set('ngShow', attrs.msgRequired + '.$error.required' );
}
};
});
The first span element with out directive shows the validation message as expected. The span element with my directive seems to always show the validation message. I am for sure not understanding the directives in angular. What am I missing or is there better ways of streamlining validation messages in angular?
There is a plunker: http://plnkr.co/edit/Gjvol8inw1DlWjHomZQw