NgMessages does not work inside directive template

My ngMessages do not work inside my directive template!

I have a myInput directive with a template and a link function, inside the template function I create a template line for the wrapped <label> and <input> .

Inside the Link function, I use require: '^form' FormController and get the name of the form. Then I put the ngMessages block after the wrapped elements.

  (function () { 'use strict'; angular .module('app.components') .directive('myInput', MyInput); /*@ngInject*/ function MyInput($compile, ValidatorService, _, LIST_OF_VALIDATORS) { return { require: '^form', restrict: 'E', controller: MyInputController, controllerAs: 'vm', bindToController: true, template: TemplateFunction, scope: { label: '@', id: '@', value: '=', validateCustom: '&' }, link: MyInputLink }; function MyInputController($attrs) { var vm = this; vm.value = ''; vm.validateClass = ''; vm.successMessage = ''; vm.errorMessage = ''; } function TemplateFunction(tElement, tAttrs) { return '<div class="input-field">' + ' <label id="input_{{vm.id}}_label" for="input_{{vm.id}}" >{{vm.label}}</label>' + ' <input id="input_{{vm.id}}" name="{{vm.id}}" ng-class="vm.validateClass" type="text" ng-model="vm.value" >' + '</div>'; } function MyInputLink(scope, element, attrs, form){ var extra = ' <div ng-messages="' + form.$name + '.' + scope.vm.id + '.$error">' + ' <div ng-messages-include="/modules/components/validationMessages.html"></div>' + ' </div>'; $(element).after(extra); } } })(); 

Using:

  <h1>Test</h1> <form name="myForm"> <my-input label="My Input" id="input1" value="vm.input1"></my-input> ------- <!-- this block is hardcoded and is working, it does not come from the directive! --> <div ng-messages="myForm.input1.$error"> <div ng-messages-include="/modules/components/validationMessages.html"></div> </div> </form> 
+5
source share
2 answers

Instead of adding the ngMessages block inside the link function, add it inside the compile function.

This is not as convenient as in link funciton due to the lack of a FormController , but it works :-)

Here is the code:

  compile: function(tElement, tAttrs){ var name = tElement.closest('form').attr('name'), fullFieldName = name + '.' + tAttrs.id; // or tAttrs.name var extra = '<div ng-messages="' + fullFieldName + '.$error">' + ' <div ng-messages-include="/modules/components/validationMessages.html"></div>' + '</div>'; $(element).after(extra); 
0
source

Here's what I did, I added the scope of myForm: '=' , and then in the directive template related to <div ng-messages="vm.myForm[vm.id].$error" >

I feel this is much cleaner than the offset in the link function.

0
source

All Articles