9

निर्देशक लिंक से निर्देशक नियंत्रक कार्यों तक कैसे पहुंचे? लिंक पर पास किए गए बेलो नियंत्रक खाली है, मैं इसमें शामिल होना चाहता हूं() छुपाएं() फ़ंक्शंस।निर्देशक लिंक में नियंत्रक कार्यों का उपयोग कैसे करें?

मेरे वर्तमान के निर्देश:

app.directive('showLoading', function() { 
    return { 
    restrict: 'A', 
    // require: 'ngModel', 
    scope: { 
     loading: '=showLoading' 
    }, 
    controller: function($scope, $element) { 
     return { 
     show: function() { 
      alert("show"); 
     }, 
     hide: function() { 
      alert("hide"); 
     } 
     }; 
    }, 
    link: function($scope, $element, $attrs, controller) { 
     $scope.$watch('loading', function(bool) { 
     if (bool) { 
      controller.show();//undefined 
     } else { 
      controller.hide(); 
     } 
     }); 
    } 
    }; 
}); 

उत्तर

30

प्रकाशन काम कर सकते हैं नियंत्रक समारोह के अंदर समस्या के कुछ प्रकार है, लेकिन नहीं सबसे अच्छा अभ्यास, क्योंकि यह गुंजाइश "प्रदूषित" करता है। अपने नियंत्रक के साथ संवाद करने का उचित तरीका require है - फिर यह अन्य आवश्यक निर्देशों के साथ link फ़ंक्शन के पैरामीटर के रूप में उपलब्ध हो जाएगा।

अन्य समस्या यह है कि आप नियंत्रक पर फ़ंक्शंस का खुलासा कैसे करते हैं - यह किसी ऑब्जेक्ट को वापस नहीं करके this.someFn का उपयोग करके किया जाता है।

app.directive('showLoading', function() { 
    return { 
    restrict: 'A', 
    require: ['ngModel', 'showLoading'], // multiple "requires" for illustration 
    scope: { 
     loading: '=showLoading' 
    }, 
    controller: function($scope, $element) { 
     this.show = function() { 
     alert("show"); 
     }; 

     this.hide = function() { 
     alert("hide"); 
     }; 
    }, 
    link: function($scope, $element, $attrs, ctrls) { 
     var ngModel = ctrls[0], me = ctrls[1]; 

     $scope.$watch('loading', function(bool) { 
     if (bool) { 
      me.show(); 
     } else { 
      me.hide(); 
     } 
     }); 
    } 
    }; 
}); 
+0

अतिरिक्त आवश्यक नियंत्रक होने पर निर्देशक नियंत्रक तक पहुंचने का वर्णन करने के लिए धन्यवाद। –

-2

आप

यहाँ कोड गुंजाइश पर काम कर रहा है ठीक

app.directive('showLoading', function() { 
    return { 
    restrict: 'AE', 
    // require: 'ngModel', 
    scope: { 
     loading: '=showLoading' 
    }, 
    controller: function($scope, $element) { 
     $scope.show = function() { 
      alert("show"); 
     }, 
     $scope.hide = function() { 
      alert("hide"); 
     } 
    }, 
    link: function($scope, $element, $attrs) { 
     $scope.$watch('loading', function(bool) { 
     if (bool) { 
      $scope.show();//undefined 
     } else { 
      $scope.hide(); 
     } 
     }); 
    } 
    }; 
}); 
+1

वास्तव में एक चिड़ियाघर कि यह उत्तर समाधान के रूप में चिह्नित किया गया था। [उत्तर] (http://stackoverflow.com/a/29195873/5788429) "नया देव" द्वारा पोस्ट किया गया वास्तव में बेहतर तरीका है। – Anton

संबंधित मुद्दे