I am learning angular, and I am trying to reduce some code that it takes to do some common things, like display error messages, by using angular directives.
One directiv
The problem is that your link function runs after the template has been compiled by Angular. So name
and error
haven't been set during compilation when ngShow
checks its attributes (thus the error where it see's a "." without anything in front of it).
ngShow
only looks at its attributes at compile, it then watches whatever expression was passed in at that point. So it never sees that the link function changes its attribute.
The html has been updated by the time you look at it, which makes it all the more confusing.
My recommendation is to use an isolate scope and pass those two attributes in that way. That'll address the timing, plus it's not a bad idea to use isolate scopes for this kind of directive anyway:
scope:{
name: '@',
error: '@'
},
The one trade off is now the form data will be on the directive's parent's scope, so we'll need to add a $parent
reference within your template:
template: '<div><p ng-show="$parent.{{name}}.$dirty">Dirty</p><p ng-show="$parent.{{name}}.$error.{{error}}"><span ng-transclude></span></p></div>',
Note I tweaked your template to separate the dirty and the required tests just to make it easier to see it working.
Here's a working fiddle