Angular.js自定义指令未多次显示

Angular.js custom directive not showing up multiple times

本文关键字:显示 指令 js 自定义 Angular      更新时间:2023-10-03

我正在编写一个Angular.js指令,以减少Twitter Bootstrap的一些样板。到目前为止,我已经创建了一个form-input元素,它按预期显示。但是,如果我将这些指令中的许多放在同一个父元素中,那么实际上只有第一个被添加并显示出来。

有人能解释一下为什么吗?

我的标记:

<form class="form-horizontal" role="form">
        <form-input type="text" target="name1" label="Name1" placeholder="Doug" ng-model="name1"/>
        <form-input type="text" target="name2" label="Name2" placeholder="Frank" ng-model="name2"/>
    </form>

app.js

var app = angular.module('app', ['ui.router']);

app.controller('FormInputController', ['$scope', '$attrs', function($scope, $attrs){
    console.log("Controller");
}]);
app.directive('formInput', function(){
    return {
        restrict: 'E',
        controller: 'FormInputController',
        transclude: true,
        replace: true,
        require: ['^ngModel'],
        template: '<div class="form-group">'
                + '<label for="{{id}}" class="col-sm-2 control-label">{{label}}</label>'
                + '<div class="col-sm-10">'
                  + '<input type="{{type}}" class="form-control" id="{{id}}" placeholder="{{placeholder}}">'
                + '</div>'
              + '</div>',
        scope: {
            id: '@',
            label: '@',
            placeholder: '@',
            type: "@"
        },
        link: function(scope, element, attrs, ctrls) {
            console.log(arguments);
        }
    };
});

如上所述,只显示"Doug"输入。

您不能在指令中使用"自关闭"标记。如果您按照以下方式更改标记,它应该可以工作:

<form class="form-horizontal" role="form">
    <form-input type="text" target="name1" label="Name1" placeholder="Doug" ng-model="name1"></form-input>
    <form-input type="text" target="name2" label="Name2" placeholder="Frank" ng-model="name2"></form-input>
</form>

基本上,HTML解析<form-input />的方式是作为一个没有关闭标记的打开标记,所以第一个指令启动了,但从未完成,这就是为什么第一个指令似乎有效,但第二个指令无效。

有关更多详细信息,请参见例如this和this。