Angular setValidity not working when HTML is produced in a Directive

Issue

I have dynamic html that i make in a directive, and it includes an input element with validation.
Example HTML produced with error message:

<input id="bob" class="personCheckbox" name="bob"
                   type="checkbox" value="bob"
                   ng-model="foobar"
                   validate-foo/>

<span style="color:red" ng-show="myForm.bob.$error.summary">Need Summary</span>

<input type="text" name="summary-bob" id="summary-bob"/>

The tag in the page for the directive that makes the HTML:

<div name-check></div>

The directive that makes the dynamic HTML, i have a watch b/c ‘people’ is from a promise:

app.directive('nameCheck', function($compile){

  return {
    replace : true,
    restrict: 'A',
    scope: false,
    link: function($scope, $element, $attrs) {

        $scope.$watch('people', function(newValue, oldValue) {
            var personNames= [];
            for(var i=0; i< newValue.length; i++){
                personNames.push(newValue[i].drugName);
            }

            if(personNames.length > 0) {
                replaceElement($scope, $element, $compile, personNames.sort());
            }
        });
    }
}
});

The replaceElement function:

function replaceElement($scope, $element, $compile, peopleNames){

  var html=  "\<div class='row'>"
            + "\<div class='small-12 columns'>"
            + "\<label>People</label>";

  for(var i=0; i < peopleNames.length; i++){

    html += "\<div>";
    html += "<input id='" + peopleNames[i] + "' ";
    html += " class='drugCheckbox' name='" + peopleNames[i] + "' ";
    html += " type='checkbox' value='" + peopleNames[i] + "' ";
    html += " ng-model='" + peopleNames[i] + "' ";
    html += " validate-foo/>";
    html += peopleNames[i];

    html += "<span style='color:red' ";
    html += " ng-show='myForm." + peopleNames[i]
    html += ".\$error.summary'>Need Summary</span>";

    html += "<input type='text' ";
    html += " name='summary-" + peopleNames[i] +"' ";
    html += " id='summary-" + peopleNames[i] + "' ";
    html += "\</div>";

}
html += "\</div></div>";

var DOM = angular.element(html);

var $e =$compile(DOM)($scope);
$element.replaceWith($e);
}

The directive that does the validation:

app.directive('validateFoo', function(){
   return{
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {

        ctrl.$parsers.unshift(function (viewValue) {
            var id= attr.id;
            if(viewValue) {
                var val= document.getElementById('summary-' + id).value;
                if(val.length == 0) {
                    ctrl.$setValidity("summary", false);

                }
                else {
                    ctrl.$setValidity("summary", true);
                    return viewValue;
                }
            }
        });
    }

}
});

The dynamic HTML produced shows on the page like it should, but the validation does not work.
When I hard code some example HTML, and use the validator, it works fine.
I cannot figure out why validation does not work (the error message will not show) when I have the HTML produced from a directive?

Solution

I had the similar issue the other day, and found solution here:

The trick is to firstly append newly created HTML snippet to DOM, and then compile. This way it will be propagated to parent FORM. Example:

directive = '<div>'+directive+'</div>';
// Do Not compile the element NOT beeing part of the DOM
//$(element).append($compile(directive)(scope));

// Firstly include in the DOM, then compile
var result = $(directive).appendTo(element);
$compile(result)(scope);

The fiddler before and after

Answered By – Radim Köhler

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.