2017-03-22 60 views
1

我想把下面的html代碼放在Angularjs指令的templateUrl的內部,但我不知道該怎麼做。如何將輸入文本和ngMessage放入指令templateUrl中?可能嗎?

我的HTML被放到裏面templateUrl

<div class="form-group" ng-class="{ 'has-error': userForm.username.$touched && userForm.username.$invalid }"> 
    <label>Name</label> 
    <input type="text" name="username" class="form-control" 
    ng-model="userForm.username" 
    ng-minlength="5" 
    ng-maxlength="10" 
    required> 

    <div class="help-block" ng-messages="userForm.username.$error" ng-if="userForm.username.$touched"> 
    <p ng-message="minlength">Your name is too short.</p> 
    <p ng-message="maxlength">Your name is too long.</p> 
    <p ng-message="required">Your name is required.</p> 
    </div> 
</div> 

我最初的指令

app.directive('nameDirective', function() { 
    return { 
    restrict: 'AE', 
    templateUrl: '/input-form/name.html' 
    }; 
}); 

我試了一下沒有指令,並能正常工作。但是當我試圖將它放入指令時,錯誤信息不會像應該出現的那樣出現。

+0

看到我的回答它應該工作 –

回答

1

需要圍繞HTML內容與form標籤。

<form name="userForm"> 
     <div class="form-group" ng-class="{ 'has-error': userForm.username.$touched && userForm.username.$invalid }"> 

    <label>Name</label> 
    <input type="text" name="username" class="form-control" 
     ng-model="username" 
     ng-minlength="5" 
     ng-maxlength="10" 
     required> 

    <div class="help-block" ng-messages="userForm.username.$error" ng-if="userForm.username.$touched"> 
    <p ng-message="minlength">Your name is too short.</p> 
    <p ng-message="maxlength">Your name is too long.</p> 
    <p ng-message="required">Your name is required.</p> 
    </div> 
    </div> 
</form> 

注入ngMessages如果您尚未

angular.module("app",['ngMessages'])

Demo

+0

感謝您提供的答案。這個對我有用。它是我正在尋找的確切答案。 – Marksmanship

4
app.directive('nameDirective', function() { 
return { 
    restrict: 'AE', 
    templateUrl: '/input-form/name.html', 
    transclude: true, 

}; 
}); 

你需要使用ng-transclude,在你的指令選項添加transclude: true,並添加ng-transclude到您的模板:

<div ng-transclude class="form-group" ng-class="{ 'has-error': userForm.username.$touched && userForm.username.$invalid }"> 
<label>Name</label> 
<input type="text" name="username" class="form-control" 
    ng-model="userForm.username" 
    ng-minlength="5" 
    ng-maxlength="10" 
    required> 

    <div class="help-block" ng-messages="userForm.username.$error" ng-if="userForm.username.$touched"> 
    <p ng-message="minlength">Your name is too short.</p> 
    <p ng-message="maxlength">Your name is too long.</p> 
    <p ng-message="required">Your name is required.</p> 
</div> 
</div> 
+1

感謝您的回答。我試過'ng-transclude',但它不適合我的問題。 @sachila的答案對我有用。但再次感謝您的回答。讚賞它。 – Marksmanship

+0

@Marksmanship投票贊成:D –

+1

好的問題,完成先生:D – Marksmanship

相關問題