AngularJS: How to access form elements when appended within a custom directive

I have been struggling with this issue for a while now. I am trying to apply some validation to my form elements with the standard format ‘FormName.ElementName.$valid’, but the name of the element is just not being found, and I can’t check it for validation.

I have realised (I think) this is because the form element is within a custom directive I made –

<div ng-repeat="Question in FormData.Questions">
    <question-type-post></question-type-post>
</div>

When outputted to my page this then looks like this (assuming there is only one question).

<form class="form-horizontal" name="myForm">
<div ng-repeat="Question in FormData.Questions">
    <question-type-post>
        <div class="form-group required" data-ng-click="selectProperties($index)" >
            <label class="col-sm-11 control-label">My Question</label> 
                <div class="col-sm-11">
                    <input type="text" name="FormElement898" class="form-control" ng-required="Question.Required" ng-model="Question.Answer" >
                    <span class="help-block">help message</span><div class="alert alert-dismissible alert-warning" ng-show="myForm.FormElement898.$dirty">
                    <p>This field is required before the audit can be submitted.</p>
                </div>
            </div>
        </div>
    </question-type-post>
</div ng-repeat="Question in FormData.Questions">

All the html within the directive is appended to the page within that directive.

app.directive('questionTypePost', function ($http, $compile) {
    return {
        restrict: 'AE',
        link: function (scope, element, attr, model) {

            var strElm = //All the html

            var compiledHtml = $compile(strElm)(scope);
            element.append(compiledHtml);
        }
    };
});

However if I place this exact same html outside of the directive then the validation DOES work so the only conclusion I can come to is that the directive is stopping the form element from being found.

How can I access the input field within this directive?


Source: forms

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.