Corey
Corey

Reputation: 351

AngularJS Dynamic Objects in template

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>'
 }

});

Upvotes: 0

Views: 30

Answers (1)

sfletche
sfletche

Reputation: 49714

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.

Upvotes: 1

Related Questions