Siyfion
Siyfion

Reputation: 979

Form validation within custom directive...?

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!)

Upvotes: 5

Views: 4761

Answers (2)

tdakhla
tdakhla

Reputation: 670

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

Upvotes: 17

Hridya
Hridya

Reputation: 1

Instead of checking for form[fieldName].$dirty && form[fieldName].$invalid just check for the existence of model value

so textTemplate looks like below

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

see the updated change in http://plnkr.co/edit/BvXkGxA0GlGip7KLXUup?p=preview

Upvotes: -3

Related Questions