2013-02-14 66 views
3

我正在處理表單輸入指令。
http://jsfiddle.net/TR9Qt/1/AngularJS - 表單驗證的指令範圍問題

<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); 
    } 
} 

});

爲什麼當我將它放入指令時不會驗證表單?

感謝,
三通

回答

1

我不是一個指令親還,但兩件事情我跳了出來:

  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/

1

有點遲到了,但你正在運行到的問題是,你正在使用一個孤立的範圍,當你試圖編譯。隔離的作用域不直接從父代繼承,但它仍然可以通過$ parent獲得。我通過將標籤屬性值附加到當前範圍來解決您的問題;這可能不是你想要的,但它解決了你眼前的問題。

 
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