gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:04:54 25 4
gpt4 key购买 nike

我正在编写一个 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>

应用程序.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”输入出现。

最佳答案

您不能为您的指令使用“自闭”标签。如果您更改 markup如下它应该工作:

<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 /> 的方式是一个没有关闭标签的开放标签,因此您的第一个指令已启动,但从未完成,这就是为什么第一个似乎有效,但第二个无效的原因。

参见例如thisthis更多细节。

关于javascript - Angular.js 自定义指令未多次显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com