2016-05-16 37 views
1

我想寫一個指令處理文件上傳(文件的base64),依賴於ng-flow 我能夠使指令工作,而不使用ngModel(綁定到範圍。 F:P),但因爲我需要用一個表格內該指令倒不如把它(以及可能使用NG-變化是一個非常不錯的功能)angularjs自定義指令文件上傳base64

angular.module('webappApp.common.directives',['flow','pascalprecht.translate', 'tmh.dynamicLocale']). 
directive('ngBase64FileUpload',function(){ 
    return { 
     restrict: 'A', 
     templateUrl: 'common/partials/base64FileUpload.tpl.html', 
     require: '^ngModel', 
     scope:{ 
      blur:'&fieldBlur', 
      focus:"&fieldFocus", 
      filename:"=" 

     }, 
     link: function (scope, element, attrs, ctrl) { 
      console.log(scope); 
      scope.processFiles = function (files) { 
       console.log(files); 
       var flowFile=files[0]; 
       //angular.forEach(files, function (flowFile, i) { 
        var fileReader = new FileReader(); 
        fileReader.onload = function (event) { 
         var f ={}; 
         //var f=event.target.result; 
         f.uri=event.target.result; 
         f.size=flowFile.size; 
         f.filename=flowFile.name; 
         ctrl.$setViewValue(f); 
        }; 
        fileReader.readAsDataURL(flowFile.file); 
       //}); 
      } 
     } 
    } 
}); 

的模板

<div class="input-group col-xs-12" flow-init="{singleFile:true}" flow-files-added="processFiles($files)"> 
<p class="input-pos-field form-control no-border nomargin" ng-if="!f"> {{filename|translate}}</p> 
<p class="input-pos-field form-control no-border nomargin" ng-if="f"> <a ng-href="{{f.uri}}" download>{{f.filename|translate}}</a></p> 
<span class="input-group-btn"> 
    <button type="button" class="icon_file" flow-btn><img src="images/file_icon.png" width="30"/><input ng-blur="blur($event)" ng-focus="focus($event)" type="file" class="hide"></button> 
</span> 

使該指令工作我也必須添加「只讀」選項,僅僅只允許下載好,如果我理解怎麼會是不錯也改變一點點的模板(按鈕圖像)

文件後我發現了一些問題,關於瞭解如何才能正確使用ngModel /解析器/格式化/ viewValue寫一個靈活的和可重複使用的指令

----編輯 指令似乎是現在的工作,但我有問題處理對照模板(顯示文件名或默認如果沒有文件上傳) 我要做的下一步是改變行爲,如果ng禁用通過(或只讀但這樣做第一第二幾乎等於)基本指令需要在按鈕使用不同的圖標(和不允許上傳文件,但只下載) plunker

回答

1

您使用ngModel.$render功能接受讀取分配給模型的值並相應地更新您的指令狀態或UI。當你有一個新的價值,你想推到模型,然後你打電話ngModel.$setViewValue

例如:

scope.f = null; 

ctrl.$render = function(){ 
    scope.f = angular.copy(ctrl.$viewValue); 
}; 

scope.processFiles = function (files) { 
    console.log(files); 
    var flowFile=files[0]; 
    //angular.forEach(files, function (flowFile, i) { 
    var fileReader = new FileReader(); 
    fileReader.onload = function (event) { 
     var f ={}; 
     //var f=event.target.result; 
     f.uri=event.target.result; 
     f.size=flowFile.size; 
     f.filename=flowFile.name; 

     ctrl.$setViewValue(f); 
    }; 
    fileReader.readAsDataURL(flowFile.file); 
    //}); 
} 

我用angular.copy創建對象的副本,以確保指令中的對象更改屬性不會導致它顯示的指令之外的變化。當調用$setViewValue時,更改只應傳播出指令。

+0

謝謝你現在正在工作,我仍然有一些問題和疑問有關的模板(添加plunker和編輯細節) – JcBobo