繁体   English   中英

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

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

我正在编写一个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 />是将其作为不带close标记的open标记,因此您的第一个指令已启动,但从未完成,这就是第一个指令似乎起作用而第二个指令无效的原因。

有关更多详细信息,请参见例如thisthis

暂无
暂无

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

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