0

我尝试使用 angular.js 创建自定义 html 表单元素。我的想法是我有一个用于表单字段布局的主模板,并粘贴到文本字段、日期字段或其他所需的模板中。

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 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>

第二个文本字段消失了。我错过了什么?

4

1 回答 1

2

关闭标签,它工作正常

<textfield id="anotherOne" label="label2" name="mytext2" value=""></textfield>

演示:http ://plnkr.co/edit/ky0Tpt8qudSLSGho2QAk?p=preview

于 2013-03-23T15:41:03.017 回答