嘗試使用jQuery文件上傳插件來創建一個文件上傳指令,這依據該指令https://gist.github.com/thoughtpalette/4726114
我需要在一個ID通過從型材ctrl.js對象成提交上傳表單的功能。
我的指令位於控制器之外,我無法將對象設置爲$ rootScope以在指令中捕獲/傳遞它。
url:在fileupload中是魔術發生的地方。通過api調用我的控制器並傳遞文件信息,並希望在profile-ctrl.js中的商家對象中的vendorId。 $scope.merchant
我不能在搗鼓後,由於項目結構不幸
我的指令:
//jqueryFileUpload-Plugin
//https://github.com/blueimp/jQuery-File-Upload
define(['jquery',
'angular',
'core',
'source/core/helpers/urlHelper.js'],
function ($, angular, core, urlHelper) {
"use strict";
return [ function ($compile) {
return {
restrict:'E',
scope: {
merchant: '=ngModel'
},
compile:function(el,attrs, scope){
var compiler = this,
elem = el,
vendorId = scope.merchant.id;
instanceFn = function() {
var currentScope = this,
fileInputDiv = $(' <span class="btn btn-success fileinput-button">'+
'<i class="icon-plus icon-white"></i>'+
'<span>Upload Logo</span>'+
'<input type="file" name="files[]" single>'+
'</span>').appendTo(elem),
fileInput = fileInputDiv.find('input'),
fileList = $('<div class="UploaderList">'+
'<table>'+
'<tr>'+
'<td>File to Upload</td>'+
'</tr>'+
'</table>'+
'</div>').appendTo(elem),
button = $('<button class="btn">Submit</button>').appendTo(elem);
button.hide();
$('<div class="uploader">').appendTo(elem);
$('</div>').appendTo(elem);
fileInput.fileupload({
url:urlHelper.vendor.uploadLogo(vendorId),
dataType: 'json',
add:function (e, data) {
button.show();
// this will add a handler which will submit this specific file
button.bind('click.uploadsubmit', function(){
data.submit();
});
$.each(data.files, function (index, file) {
$("<tr><td>"+file.name+"</td><td></td><tr>").appendTo(fileList.find('table:first'));
});
},
// for each file
done: function (e, data) {
button.hide();
var result = "",
r = data.result,
file = data.files[0]; // we only support single file upload by now
// error
// CHANGE THIS PART FOR YOUR REQUIREMENTS (I have a json repsonse)
if(r.success !== undefined && r.success === false){
result = "<span class='error'>Unknown error</span>";
if(r.errors !== undefined && r.errors.length > 0 && r.errors[0].message !== undefined)
{
result = "<span class='error'>"+r.errors[0].message+"</span>";
}
}
else{
result = "<span class='success'>OK</span>";
}
$("td:contains('"+file.name+"')").next().html(result);
},
progressall:function (e, data) {
var progress = parseInt(data.loaded/data.total * 100, 10);
},
// called only once... (wen submit button is clicked)
start:function(e){
// we start the upload, so we do also cleanup jobs right now:
button.unbind('click.uploadsubmit'); // importan - remove all event handlers
button.hide();
fileInputDiv.hide();
}
});
};
return instanceFn;
}
};
}];
});
指令通過HTML召喚:
<jquery-File-Upload ng-model="merchant"></jquery-File-Upload>
所以馬上 商家返回的指令中未定義。有人可以幫我通過嗎?
編譯函數的第三個參數不是範圍,它是一個transclude連接函數。我相信你定義的instanceF是你的鏈接函數,對嗎?如果是這樣,它的第一個參數是範圍,商家應該被定義。 –
這是正確的,但現在我發現我的指令在我的商家範圍設置之前執行,因此沒有設置值。通過將scope.merchant.id放入fileupload的啓動函數進行測試。隨意張貼爲答案:} –