5

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

4

2 回答 2

17

将模板包装在它自己的 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>';

您遇到的问题是,在创建隔离范围(范围 { ... })时,您无权访问父表单或任何父范围。IMO,这绝对是一件好事,因为您不希望您的指令硬编码父表单的名称,并且它将您的指令保持为一个独立的单元。

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

于 2013-08-12T12:54:26.897 回答
-3

而不是form[fieldName].$dirty && form[fieldName].$invalid只检查模型值的存在

所以 textTemplate 如下所示

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>';

请参阅http://plnkr.co/edit/BvXkGxA0GlGip7KLXUup?p=preview中的更新更改

于 2013-08-12T12:10:27.803 回答