Article From:https://segmentfault.com/q/1010000011697150
Question:

To upload a file using angular’s input, the ng-change query on the Web does not trigger, but is written as onchange = “angular. element (this). scope (). upload (this,’adv’)”But it’s still wrong, I don’t understand. I begged for advice.

Answer 0:

fileIt will not trigger. Suggestions are encapsulated into instructions. I wrote several in my early years.

  1. angularjsUploading instruction
  2. Angularjs upload instruction with progress bar
angular.module('xl-angular-upload', [])
    .directive('angularUpload', [function () {
        return {
            restrict: 'E',
            require: 'ngModel',
            template: '<div class="xl-angular-upload">\n    <!--upload button-->\n    <button class="xl-btn btn-primary">Upload n & lt; input type = "file" / & gt;  n & lt; / button & gt;  n & lt;! - upload queue - & gt;  n & lt;Div class= "queue" > \n < div class= "item" ng-repeat= "item item";IV class= "info" > \n < div class= "no" > {{$index+1}}< >< div class= "name" > {{item.name}}< /div> \n < div class= "<";Size/1024).ToFixed (2)}}KB< /div> \n < /div> \n < div class= "div"Bar "> \n < div class=" process "style=" width:{{item.process}}% ">"; < width:{{item.process}}%;< /div> \n < /div> \n < /div> \n< /div> 'Replace:True,Link: function (scope, ele, attrs, CTRL) {/ / necessary attribute detectionIf ((attrs.action) {Throw new Error ('please set up upload action' ');}/ / initializationScope.queue = [];Var file = angular.element (documen)T.querySelector ('.xl-angular-upload>.Xl-btn> input[type= "file")];Var files =[];Attrs.accept & & file.attr ('accept', attrs.accept);AttrS.multiple & & file.attr ('multiple', attrs.multiple);File.bind ("change", fun)Ction (E) {Scope.$apply (function () {Scope.queue = [];For (VaR I in e.target.files) {If (/^\d+$/.tes)T (I)) {E.target.files[i].process = 0;Scope.queue.push (e.target.files[i]);}}});/ / ready to uploadScope.queue.forEach (function (ITE)M) {Var data = new FormData;Data.append (attrs.name)'file'(item);Var XHR = new XMLHttpRequest ();XHr.open ('POST', attrs.action, true);/ / event monitoringXhr.onreAdystatechange = function () {If (xhr.readyState = = 4 & & xhr.st)Atus = = 200) {/ / upload completed.Var resp = JSON.parse (xhr.responseText);If (resp.error) {Throw new Error (resp.error);} else {Files.push (RESP);Ctrl.$setViewValue (files);}}};Xhr.onerror = function (error) {Throw new Error (error);};Xhr.upload & & (xhr.upload.onprogress = fUnction (E) {If (e.lengthComputable) {Scope.$apply (function () {Item.process = parseInt ((e.loaded / E).total) * 100);});}});Xhr.send (data);});});}}"]);

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *