我需要知道是否可能,并且在是的情况下如何做到这一点。
我的表单输入如下:
<input type="text" class="form-control" name="dirinput"
placeholder="Placeholder"
translate
translate-attr-placeholder="{{ placeholder }}"
ng-model-options="{ debounce: 500 }">
我希望,围绕这个输入,包装div来管理标签和错误(如果有的话)(如果出现错误则显示一个字符串)。 我还需要能够将指令放在input元素上。
目前我要为每个输入编写所有这些代码
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
<div class="form-group label-static"
ng-class="{ 'has-error': relatedForm.first_name.$invalid && relatedForm.first_name.$dirty,
'has-success' : relatedForm.first_name.$valid }">
<label for="input-first_name"
class="control-label" translate>
FIRST_NAME
</label>
<input type="text" class="form-control"
id="input-first_name" name="first_name"
placeholder="First name"
ng-model="relatedCtrl.data.first_name"
ng-model-options="{ debounce: 500 }"
required autofocus>
<p class="help-block"
ng-if="relatedForm.first_name.$error.required" translate>
ERR_FIRST_NAME_REQUIRED
</p>
</div>
</div>
如果你能看到很多“重复”的代码,我就会徘徊,如果有可能避免这种情况。
非常感谢
答案 0 :(得分:0)
您可以使用Angular指令的 transclude
功能:
myModule.directive('myInput', function() {
return {
transclude: true,
templateUrl: 'my-transclude.html'
};
});
在my-transclude.html
:
<div class="wrapper>
<div ng-transclude></div>
</div>
在您的HTML中:
<my-input>
<input type="text" class="form-control" name="dirinput"
placeholder="Placeholder"
translate
translate-attr-placeholder="{{ placeholder }}"
ng-model-options="{ debounce: 500 }">
</my-input>
当然,如果没有其他HTML文件,您可以直接使用template
代替templateUrl
,但templateUrl
是一种很好的做法。
答案 1 :(得分:0)
是的,您可以创建包含输入的transclude指令。
jsfiddle上的实例。
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
});
myApp.directive("wrapExample", function() {
return {
restrict: 'E',
transclude:true,
scope: {
proccess: "=",
},
template:'<div><label>I\'m before wrapped label</label><div ng-transclude></div><div>I\'m after wrapped div</div></div>',
link: function(scope, element, attrs) {
},
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<wrap-example>
<input value="input" />
</wrap-example>
</body>
&#13;