kkochanski kkochanski - 6 months ago 16
AngularJS Question

AngularJS make directive from ngMessages

I want to create a directive which allow me to generate validation message near input - based on ngMessages(as in example).I have this working HTML example:


<div class="field">
<div class="ui right icon input">
<input type="email" name="email" ng-model="vm.user.email" placeholder="E-mail" required>
<i class="at icon"></i>
</div>
<div ng-messages="vm.signUpForm.email.$error" ng-show="vm.signUpForm.$submitted">
<div ng-messages-include="shared/validation/formErrorMessages.html"> </div>
</div>
</div>


My current directive:

var app = angular.module('app.directives', []);

app.directive('formError', function() {
return {
restrict: 'AE',
replace: 'false',
scope: {
statement: '@',
error: '@'
},
template: '<div ng-messages="error" ng-show="true"><div ng-messages-include="shared/validation/formErrorMessages.html"></div></div>'
};
});


And how I tried to run it:



<div form-error error="{{ vm.signUpForm.email.$error }}" statement="{{ vm.signUpForm.$submitted }}"></div>


It's not working - message won't appear - without any error. On message show I will also want to add class 'error' to 'div.field', but it should be easy.

Any idea how to make this directive work or maybe how to handle this in another, more comfortable way?

Answer

You made a a mistake, you should pass attributes to directive with

scope: {
      statement: '=',
      error: '='
    },

@ biding is for passing string values, not objects and error is an object, so passing it that way will not work as expected. Of course you could use attr.$observe and JSON.parse, but that is not what you wanna do here.

https://plnkr.co/edit/iRRPqLpmqdQltNjw35Nb?p=preview

Comments