AngularJS - 带有表单验证的指令范围问题

时间:2013-02-14 11:50:43

标签: angularjs angularjs-directive

我正在处理表单输入指令 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);
    }
}

});

当我将表单放入指令时,为什么表单不会验证?

谢谢,
三通

2 个答案:

答案 0 :(得分:1)

我还不是指令专家,但有两件事突然出现在我身上:

  1. 除非在ng-repeat中使用它,否则你不需要编译你的指令。
  2. 您的指令与标签而不是表单字段相关联。

    <input 
        ng-form-field
        type="email" 
        name="test_email"
        ng-model="formData.testEmail" 
        placeholder="Email" 
        required />
    
  3. http://jsfiddle.net/sharondio/c8hwj/

答案 1 :(得分:1)

派对有点晚了,但是你遇到的问题是你在编译时使用了一个独立的范围。隔离范围不直接从父级继承,但仍可通过$ parent获得。我通过将label属性值附加到当前范围来解决您的问题;这可能不是你想要的,但它解决了你当前的问题。

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

myApp.directive('ngFormField', function ($compile) {
    var labelTemplate = '{{label}}';
    var inputTemplate = '' +

        '' +
        'Tell us your email.' +
        'This is not a valid email.' +
        '';
    return {
        // append
        replace: true,
        // attribute restriction
        restrict: 'E',
        // linking method
        link: function ($scope, element, attrs) {
            $scope.label = attrs.label;
            element.html(labelTemplate + inputTemplate);
            $compile(element.contents())($scope);
        }
    };
});

工作plunker