ฉันมีแบบฟอร์มที่ใช้มาร์กอัปจาก Bootstrap ดังต่อไปนี้:
<form class="form-horizontal">
<fieldset>
<legend>Legend text</legend>
<div class="control-group">
<label class="control-label" for="nameInput">Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="nameInput">
<p class="help-block">Supporting help text</p>
</div>
</div>
</fieldset>
</form>
มีรหัสสำเร็จรูปจำนวนมากอยู่ในนั้นซึ่งฉันต้องการลดเป็นคำสั่งใหม่ - การป้อนรูปแบบดังต่อไปนี้:
<form-input label="Name" form-id="nameInput"></form-input>
สร้าง:
<div class="control-group">
<label class="control-label" for="nameInput">Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="nameInput">
</div>
</div>
ฉันทำงานได้ดีมากผ่านเทมเพลตง่ายๆ
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {
label: 'bind',
formId: 'bind'
},
template: '<div class="control-group">' +
'<label class="control-label" for="{{formId}}">{{label}}</label>' +
'<div class="controls">' +
'<input type="text" class="input-xlarge" id="{{formId}}" name="{{formId}}">' +
'</div>' +
'</div>'
}
})
อย่างไรก็ตามเมื่อฉันเพิ่มฟังก์ชันการทำงานขั้นสูงมากขึ้นทำให้ฉันติดขัด
ฉันจะรองรับค่าเริ่มต้นในเทมเพลตได้อย่างไร
ฉันต้องการแสดงพารามิเตอร์ "type" เป็นแอตทริบิวต์ที่ไม่บังคับในคำสั่งของฉันเช่น:
<form-input label="Password" form-id="password" type="password"/></form-input>
<form-input label="Email address" form-id="emailAddress" type="email" /></form-input>
"text"
แต่ถ้าไม่มีอะไรจะระบุฉันต้องการที่จะเริ่มต้นกับ ฉันจะสนับสนุนสิ่งนี้ได้อย่างไร?
ฉันจะปรับแต่งเทมเพลตตามการมี / ไม่มีคุณลักษณะได้อย่างไร
ฉันยังต้องการที่จะสนับสนุนแอตทริบิวต์ "ที่จำเป็น" หากมีอยู่ เช่น:
<form-input label="Email address" form-id="emailAddress" type="email" required/></form-input>
หากrequired
มีอยู่ในคำสั่งฉันต้องการเพิ่มลงในสิ่งที่สร้างขึ้น<input />
ในเอาต์พุตและไม่ต้องสนใจเป็นอย่างอื่น ฉันไม่แน่ใจว่าจะบรรลุเป้าหมายนี้ได้อย่างไร
ฉันสงสัยว่าข้อกำหนดเหล่านี้อาจก้าวไปไกลกว่าเทมเพลตทั่วไปและต้องเริ่มใช้ขั้นตอนการคอมไพล์ล่วงหน้า แต่ฉันไม่สามารถเริ่มต้นได้
type
ตั้งค่าแบบไดนามิกผ่านการผูกเช่นtype="{{ $ctrl.myForm.myField.type}}"
เหรอ? ฉันตรวจสอบวิธีการทั้งหมดด้านล่างแล้วและไม่พบวิธีแก้ไขใด ๆ ที่จะใช้ได้ในสถานการณ์นี้ ดูเหมือนว่าฟังก์ชัน template จะเห็นค่าตามตัวอักษร ของแอตทริบิวต์เช่น แทนtAttr['type'] == '{{ $ctrl.myForm.myField.type }}'
tAttr['type'] == 'password'
ฉันงงงวย