简体   繁体   English

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

[英]Angular.js custom directive not showing up multiple times

I've got a Angular.js directive I'm writing to reduce some boilerplate with Twitter Bootstrap. 我正在编写一个Angular.js指令,以减少Twitter Bootstrap的样板。 So far I've created a form-input element and it displays as expected. 到目前为止,我已经创建了一个form-input元素,它可以按预期显示。 However, if I place many of these directives in the same parent element, only the first one actually gets added and shows up. 但是,如果我将许多指令放在同一父元素中,则实际上只会添加第一个指令并显示出来。

Can anyone shed some light on why? 谁能阐明为什么?

My markup: 我的标记:

<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 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);
        }
    };
});

As stated above, only the "Doug" input shows up. 如上所述,仅显示“ Doug”输入。

You can't use "self closing" tags for your directives. 您不能在指令中使用“自动关闭”标签。 If you change your markup as follows it should work: 如果您按照以下方式更改标记 ,则它应该可以工作:

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

Basically, the way that HTML parses <form-input /> is as an open tag without a close tag, so your first directive is started, but never finished, which is why the first one appears to work, but the second one not. 基本上,HTML解析<form-input />是将其作为不带close标记的open标记,因此您的第一个指令已启动,但从未完成,这就是第一个指令似乎起作用而第二个指令无效的原因。

See eg this and this for more details. 有关更多详细信息,请参见例如thisthis

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM