2013-08-22 13 views
23

HTML में साथ फार्म मान्य करने के लिए:कैसे इनपुट [प्रकार = फ़ाइल] AngularJS

<form name="form"> 
    <input type="file" ng-model="document" valid-file required> 
    <input type="submit" value="{{ !form.$valid && 'invalid' || 'valid' }}"> 
</form> 

कस्टम निर्देश इनपुट के लिए सुनने के लिए [type = फ़ाइल] परिवर्तन:

myApp.directive('validFile',function(){ 
    return { 
     require:'ngModel', 
     link:function(scope,el,attrs,ngModel){ 

      //change event is fired when file is selected 
      el.bind('change',function(){ 
       scope.$apply(function(){ 
        ngModel.$setViewValue(el.val()); 
        ngModel.$render(); 
       }); 
      }); 
     } 
    }; 
}); 

फ़ाइल निम्न चयनित हो त्रुटि कंसोल में प्रकट होता है:

Error: InvalidStateError: DOM Exception 11 Error: An attempt was made to use an object that is not, or is no longer, usable.

plunkr साथ प्रयास करें: http://plnkr.co/edit/C5j5e0JyMjt9vUopLDHc?p=preview

निर्देश के बिना इनपुट फ़ाइल फ़ील्ड की स्थिति को फॉर्म में धक्का नहीं दिया जाएगा। $ मान्य। कोई विचार है कि मुझे यह त्रुटि क्यों मिलती है और इसे कैसे ठीक किया जाए?

उत्तर

29
की NgModelController.$render()

Called when the view needs to be updated. It is expected that the user of the ng-model directive will implement this method.

आप $ लागू प्रस्तुत करना() इसे कहते हैं की जरूरत संदर्भ से

। आप AngularJS को अद्यतन करने 1.2.x टुकड़ा अब ठीक से काम नहीं लगता है और फ़ाइल इनपुट चयनित फ़ाइल मूल्य के साथ नहीं है चिपक जाता है के बाद इस

myApp.directive('validFile', function() { 
    return { 
     require: 'ngModel', 
     link: function (scope, el, attrs, ngModel) { 
      ngModel.$render = function() { 
       ngModel.$setViewValue(el.val()); 
      }; 

      el.bind('change', function() { 
       scope.$apply(function() { 
        ngModel.$render(); 
       }); 
      }); 
     } 
    }; 
}); 

DEMO

+0

+1 वाह महान, त्रुटि चला गया है धन्यवाद !! –

+1

काम करता है। अब मुझे सीखना है क्यों। कोणीय वूडू, आदमी है। – DrHall

+0

मीठा! मेरे लिए सही काम किया +1! – user1429166

4

की तरह कुछ कर सकते हैं, फॉर्म को अनुपयोगी बनाते हुए। निर्देश वापस अपने मूल एक के लिए बदल रहा है, और ngModel.$render() को हटाने के लिए यह एक आकर्षण की तरह काम दिखता है:

.directive('validFile', function() { 
    return { 
    restrict: 'A', 
    require: '?ngModel', 
    link: function (scope, el, attrs, ngModel) { 
     el.bind('change', function() { 
     scope.$apply(function() { 
      ngModel.$setViewValue(el.val()); 
     }); 
     }); 
    } 
    }; 
+0

यह पूरी तरह से काम करता है, धन्यवाद :) –

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