मैं एक ऐसी ही समस्या के साथ इस पृष्ठ पर उतरा, एक कस्टम निर्देश के साथ एक ngModel बाध्यकारी । सवाल कुछ साल पुराना है, लेकिन शायद मेरा समाधान किसी और की मदद करेगा।
सबसे पहले, index.html में, मैं कुछ कस्टम-अप विशेषताओं के साथ अपने कस्टम निर्देश का उपयोग कर रहा हूं। एचटीएमएल में डैश केस नोट करें। गुण मान वे हैं जो मैं निर्देश में उपयोग करना चाहता हूं।
index.html
<div>
<form name="userInfo">
<my-custom-directive for-model="ctrl.userInput"
for-label="Enter User Info"
for-other="more info for the directive">
<my-custom-directive>
</form>
</div>
// check to see the binding.
{{ ctrl.userInput }}
इसके बाद, partial.html में, मैं यह देखने के लिए जब निर्देश ठीक से काम कर रहा है कुछ डिफ़ॉल्ट मान सेट करने के लिए जा रहा हूँ, और जब मैं चूक देखते हैं।
partial.html
<div class="form-group">
<label>blankLabel</label>
<input type="text"
class="form-control"
ng-model="modelBlank">
</div>
निर्देश को कुछ अलग वाक्यविन्यास की आवश्यकता है, जो शायद सबसे आम समस्या है। मैं एक चर को परिभाषित करना चाहता हूं, क्योंकि मैं कई विशेषताओं को असाइन कर रहा हूं। फिर वैरिएबल पर .attr() को कॉल करें और उस नई जानकारी को पास करें जिसे आप लागू करना चाहते हैं। इस मामले में, शब्दशः 'एनजी-मॉडल' और index.html में सेट कस्टम विशेषता का मान।
directive.js
.directive('myCustomDirective', function() {
return {
templateUrl: 'partial.html',
compile: function (element, attributes) {
// Find the right element in the partial and assign a variable
var inputTag = element.find('input');
// use .attr() on the variable and pass it two arguments.
inputTag.attr('ng-model', attributes.forModel);
// Find a different element in the partial and replace the text.
var labelTag = element.find('label');
labelTag.html(attributes.forLabel);
}
};
})
आप कंसोल का उपयोग कर सकते हैं।लॉग (तत्व), लेकिन यह बहुत सारी जानकारी उत्पन्न करने जा रहा है। कस्टम मान पर एनजी-मॉडल सेट देखने के लिए पृष्ठ लोड होने के बाद तत्व का निरीक्षण करने के लिए बेहतर। यदि यह सही ढंग से जुड़ा हुआ है, तो index.html पृष्ठ पर {{ctrl.userInput}} को फ़ॉर्म में टाइप किए गए टेक्स्ट को दिखाना चाहिए।
यह बहुत काम है, लेकिन अब myCustomDirective अलग जानकारी में पारित के साथ पुन: उपयोग किया जा सकता है:
<my-custom-directive for-model="ctrl.userName"
for-label="Enter Your Name:"
for-other="more info for the directive">
<my-custom-directive>
<my-custom-directive for-model="ctrl.userSelection"
for-label="Make a selection:"
for-other="more info for the directive">
<my-custom-directive>
व्यक्तिगत रूप से, मैं सामान सहित इस विधि के साथ गुण या कोणीय निर्देशों जोड़ने में कोई समस्या थी कभी नहीं किया है यूआईबी-टाइपहेड की तरह। बस एचटीएमएल और जावास्क्रिप्ट के बीच वाक्यविन्यास मतभेदों का पालन करना याद रखें।
कृपया अपना निर्देश कोड –
साझा करें, लेकिन अभी तक कोई भाग्य नहीं है। –