Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation within custom directive...?

Tags:

angularjs

I have a HTML form that is being built up dynamically from a given "product" object and the fields that it has, allowing the user to modify the associated data. I am using a custom "editor" directive to handle the creation of the HTML elements needed to allow the user to update the data.

An example can be seen here: http://plnkr.co/edit/2fAVVpwTHFgxwTq4eAMI

Firstly, I'm not sure if this is the best way to achieve this, but it does (so far) seem to work okay. (Any other idea's welcome!)

However, I want to add validation rules to the controls, eg. require so that a message appears when the input is left empty. I have attempted to add these validation rules into the code (as seen in the template in the directive), but it never fires. I'm pretty sure it's something to do with me getting my scope wires-crossed somewhere... AngularJS Batarang is showing on the main scope an object of:

form: {
  {{fieldName}}: {}
}

Which is obviously wrong (and nonsense!)

like image 987
Siyfion Avatar asked Aug 12 '13 11:08

Siyfion


People also ask

Which form needs custom validator directive that wrap validation function for form validation?

Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.

How do I create a custom validator?

in order to implement a custom validation directive, we need to implement the Validator interface, which only has the validate method. the validate method is going to call the validation creation function, and pass the control reference (the password control in this case) to the validator.


1 Answers

Wrap the template in its own ng-form:

textTemplate =  '<div ng-form="editor">' +
                  '<input id="{{fieldName}}" name="{{fieldName}}" type="text" ng-model="fieldData.data" required>' +
                  '<div ng-show="editor.$dirty && editor.$invalid">Invalid:' +
                      '<span ng-show="editor.$error.required">Some validation error!</span>' +
                  '</div>' +
                '</div>';

The issue you're running into is that when creating an isolate scope (scope { ... }), you don't have access to the parent form, or any parent scope for that matter. IMO, this is definitely a good thing since you don't want your directive to hard-code the name of the parent form, and it keeps your directive as a self-contained unit.

Code: http://plnkr.co/edit/qCjs16tuwVjSNzJdkk71?p=preview

like image 191
tdakhla Avatar answered Sep 20 '22 14:09

tdakhla