我想将下面的html代码放在Angularjs指令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 :(得分: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 :(得分:1)
需要使用form
代码包围html内容。
<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'])