-
-
Save yusufola/3544fe9d322426051c247fe56e36e622 to your computer and use it in GitHub Desktop.
angular image upload directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(['jquery', 'message'], function($, scojs_message) { | |
'use strict'; | |
/** | |
* The image upload directive | |
* @author: kehefu | |
* @version: 0.1.0, 2016-12-27 | |
*/ | |
var uploadModule = angular.module('upload', []); | |
uploadModule.directive('upload', ['$window', function($window) { | |
var helper = { | |
isImage: function(file) { | |
var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; | |
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; | |
} | |
}; | |
return { | |
restrict: 'E', | |
scope: { | |
server: '=', //don't use serverUrl,can't get the value | |
imgurl: '=?', | |
}, | |
template: '<div class="fileUpload-box" >' + | |
'<div class="fileUpload imgUpload" >' + | |
'<input accept="image/*" class="upload" type="file"' + | |
'onchange="angular.element(this).scope().onchange(this)" >' + | |
'<img ng-if="imgurl" ng-src="{{imgurl}}" class="thumb" />'+ | |
'</div>'+ | |
'<i class="close-icon" ng-click="delImg()" ng-if="imgurl" ></i>'+ | |
'</div>', | |
link: function(scope, element, attributes) { | |
scope.onchange = function(that) { | |
if(!helper.isImage(that.files[0])){ | |
$.scojs_message('文件类型错误', $.scojs_message.TYPE_ERROR); | |
return; | |
} | |
if(!scope.server){ | |
$.scojs_message('server不能为空', $.scojs_message.TYPE_ERROR); | |
return; | |
} | |
var formData = new FormData(); | |
formData.append("file", that.files[0]); | |
$.ajax({ | |
url: scope.server, | |
data: formData, | |
processData: false, | |
contentType: false, | |
type: 'POST', | |
success: function(result) { | |
if (result.status === 1) { | |
$.scojs_message('图片上传成功', $.scojs_message.TYPE_OK); | |
scope.imgurl=result.data[0]; | |
scope.$apply(); | |
$(that).val(''); | |
} else { | |
$.scojs_message(result.showMessage, $.scojs_message.TYPE_ERROR); | |
} | |
} | |
}); | |
scope.delImg=function(index){ | |
scope.imgurl=''; | |
} | |
$(".fileUpload-box").on("mouseenter",function () { | |
$(this).find(".close-icon").show(); | |
}); | |
$(".fileUpload-box").on("mouseleave",function () { | |
$(this).find(".close-icon").hide(); | |
}); | |
} | |
} | |
}; | |
}]); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment