我尝试使用angular.js创建自定义html表单元素。我的想法是,我有一个maintemplate for formfield-layout并粘贴到textfield,datefield或其他所需的模板中。
var app = angular.module("myApp", []);
app.controller("MainCtrl", function ($scope) {
$scope.window = window;
});
// create general formfield-layout
function buildFormTemplate(innerTemplate) {
var t = '<div class="control-group">'
+ '<label class="control-label" for="{{x.id}}">{{x.label}}';
t += '<span ng-show="x.required" class="required">*</span>',
t += '</label><div class="controlls">';
t += innerTemplate;
t += '</div>';
t += '</div>';
return t;
}
app.directive("textfield", function() {
return {
restrict: "E",
scope: {},
replace: true,
template: buildFormTemplate('<input id="{{x.id}}" type="text" name="{{x.name}}" value="{{x.value}}" />'),
link: function(scope, elm, attrs) {
scope.x = attrs;
}
};
});
此代码的工作方式与我预期的相同,但如果我有多个textfield元素,则只会渲染一个。其他文本字段元素消失了。
<textfield id="myLabel" label="label1" name="mytext1" value="with label"/>
<textfield id="anotherOne" label="label2" name="mytext2" value=""/>
呈现
<div class="control-group" id="myLabel" label="label1" name="mytext1" value="with label">
<label class="control-label ng-binding" for="myLabel">
label1<span ng-show="x.required" class="required" style="display: none;">*</span></label>
<div class="controlls">
<input id="myLabel" type="text" name="mytext1" value="with label">
</div>
</div>
第二个文本字段消失了。我错过了什么?
答案 0 :(得分:2)
关闭标签,工作正常
<textfield id="anotherOne" label="label2" name="mytext2" value=""></textfield>