0

I am working on a directive and I had form validation working by hard-coding the ng-show to form.birthdate.$touched && form.birthdate.$error.required. After getting this working I set out to removing the portion of that string where i'd hardcoded the name of the input to birthdate. See below in the code where I have two spans with the this field is required message. The bottom one works, the top one doesn't. If I look at it in the HTML elements panel they look identical so it seems like it should work but things are not being bound correctly. Any idea how to solve this problem?

angular.module('MyModule').directive('vrDatepicker', function() {

return {

scope: {
  dateModel: '='
},
link: function(scope, element, attrs, ctrls) {
    scope.id = attrs.id;
    scope.name = attrs.name;
    scope.required = attrs.required;
    scope.form = ctrls[0];
},

controller: ['$scope', function($scope) {
  // Removed b/c it doesn't matter
}],

template: '<p class="input-group">\
             <input type="text" \
                    class="form-control"\
                    datepicker-popup="MMM d, yyyy"\
                    ng-model="dateModel"\
                    is-open="opened"\
                    show-weeks="false"\
                    close-text="Close" />\
             <span class="input-group-btn">\
               <button type="button"\
                       class="btn btn-default"\
                       ng-click="open($event)">\
                 <i class="glyphicon glyphicon-calendar"></i>\
               </button>\
             </span>\
             <span ng-show="form[\'{{name}}\'].$touched && form[\'{{name}}\'].$error.required" class="text-danger">This field is required</span>\  // ### This one doesn't work
             <span ng-show="form.birthdate.$touched && form.birthdate.$error.required" class="text-danger">This field is required</span>'\ // ### This one works
           </p>'
 }

});
1
  • If you use form[name] instead of form[\'{{name}}\'] it should work. At least regarding to the syntax. Commented Jul 24, 2015 at 15:55

1 Answer 1

1

This should work

<span ng-show="form[name].$touched && form[name].$error.required" class="text-danger">This field is required</span>

Everything within the string assigned to ng-show will be interpolated so you don't need all that extra syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow.. How did I not try this. Thank you! I tried 15 different ways of circumventing what It thought was a much deeper issue.
I'm guessing we all had to learn that one the hard way... :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.