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); 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> ------- <div ng-messages="myForm.input1.$error"> <div ng-messages-include="/modules/components/validationMessages.html"></div> </div> </form>
source share