jackdh jackdh - 7 months ago 22
Javascript Question

Padding form into templateURL to be used with ngMessages

I'm new to angular and trying my hand at directives.

I would like to be able to use

<div ng-messages="form.$error">
<div ng-message="required">You did not enter a field</div>
</div>


Within a custom directive like so,

<div class="form-group">
<label class="form-label" for="s-input-{{name}}">
{{text.human}}
<span ng-if="text.subtext" class="form-hint">{{text.subtext}}</span>
</label>

<select ng-required="required" ng-model="model" class="form-control" id="s-input-{{name}}" name="{{name}}" ng-options="t for t in text.select"></select>
<div ng-messages="form.$error">
<div ng-message="required">You did not enter a field</div>
</div>
</div>


I can get it to work by passing using ng-messages below the directive element but not in it.

Although I really can't figure out how to pass the form in to the template so it can be accessed by ng-messages.

I've set up a plunker to show you my bare bones setup.

http://plnkr.co/edit/ELx6Fd2eLN4CJjEnzRGM?p=preview

I know I need to require the form with
require: '^form',
although I'm not sure how to use/access in the template URL.

I've been banging my head for a while so would really appreciate some help! Thanks.

JC. JC.
Answer

When you require the form directive with require: '^form' you then access that FormController in the link function. You can then simply attach that controller to the directive's scope like so:

link: function(scope, element, attributes, formController) {
    scope.form = formController;
}

Then reference it in the template:

<div ng-messages="form.$error">
    <div ng-message="required">You did not enter a field</div>
</div>