3

フォーム入力ディレクティブに取り組んでいます。
http://jsfiddle.net/TR9Qt/1/

<form name="form">
<ng-form-field label="Email validation NOT working"></ng-form-field>
<label for="test_email">Test Email with working validation</label>
<input type="email" name="test_email"
ng-model="formData.testEmail" placeholder="Email" required />
<div class="error-message" ng-show="form.test_email.$dirty && form.test_email.$invalid"> <span ng-show="form.test_email.$error.required">Tell us your email.</span>

    <span
    ng-show="form.test_email.$error.email">This is not a valid email.</span>
</div>

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

myApp.directive('ngFormField', function ($compile) {
var labelTemplate = '<label for="user_email">{{label}}</label>';
var inputTemplate = '<input type="email" name="user_email" ng-model="formData.email" placeholder="Email" required />' +

    '<div class="error-message" ng-show="form.user_email.$dirty && form.user_email.$invalid">' +
    '<span ng-show="form.user_email.$error.required">Tell us your email.</span>' +
    '<span ng-show="form.user_email.$error.email">This is not a valid email.</span>' +
    '</div>';


return {
    transclude: true,
    scope: {
        label: '@'
    },
    // append
    replace: true,
    // attribute restriction
    restrict: 'E',
    controller: function ($scope, $element, $attrs) {},
    // linking method
    link: function ($scope, element, attrs) {
        element.html(labelTemplate + inputTemplate);

        $compile(element.contents())($scope);
    }
}

});

フォームをディレクティブに入れたときにフォームが検証されないのはなぜですか?

ありがとう、
ティー

4

2 に答える 2

1

私はまだディレクティブの専門家ではありませんが、次の 2 つのことが気になりました。

  1. ng-repeat で使用されていない限り、ディレクティブをコンパイルする必要はありません。
  2. ディレクティブは、フォーム フィールドではなくラベルに結び付けられました。

    <input 
        ng-form-field
        type="email" 
        name="test_email"
        ng-model="formData.testEmail" 
        placeholder="Email" 
        required />
    

http://jsfiddle.net/sharondio/c8hwj/

于 2013-02-14T18:16:16.893 に答える