我是angularjs的新手我试图通过文件浏览器指令中的隔离范围上传来实现图像预览。
这是我的HTML代码
<div class="content">
<div class="field">
<label for="form-bridge-logo1">Logo 1</label>
<input id="form-bridge-logo1" type="text" value="" ng-model="myFile.name" />
<button class="clear-file" ng-if="myFile.name" ng-click="clear(myFile)"></button>
<input type="file" id="browse-file-logo1" ng-model="test" name="cover" file-browser="myFile" my-file="myFile" multiple data-logo-type="primary" class="browse-file-input" accept="image/jpg, image/jpeg, image/png"/>
<label for="browse-file-logo1" class="browse-btn">Browse</label>
</div>
<span class="remove-file" ng-if="myFile.name" ng-click="clear(myFile)">Remove</span>
</div>
<div class="content">
<div class="field">
<label for="form-bridge-logo2">Logo 2</label>
<input id="form-bridge-logo2" type="text" ng-model="myFile1.name"/>
<button class="clear-file" ng-if="myFile1.name" ng-click="clear(myFile1)"></button>
<input type="file" id="browse-file-logo2" name="cover" file-browser="myFile1" multiple data-logo-type="secondary" class="browse-file-input" accept="image/jpg, image/jpeg, image/png"/>
<label for="browse-file-logo2" class="browse-btn">Browse</label>
</div>
<span class="remove-file" ng-if="myFile1.name" ng-click="clear(myFile1)">Remove</span>
</div>
我希望在以下div中预览图像
<div class="rectangle-11">
<div ng-if="myFile.name" class="preview-container">
<img ng-src="{{imageSrcForPreview}}" alt="Logo 1" class="preview">
</div>
<div ng-if="myFile1.name" class="preview-container">
<img ng-src="{{imageSrcForPreview}}" alt="Logo 2" class="preview">
</div>
</div>
我的指示如下
module.exports = function($log, $parse, backendService, sharedServices, fileReader) {
return {
restrict: "A",
scope: {
myFile: "="
},
link: function(scope, element, attrs, sharedServices) {
var model = $parse(attrs.fileBrowser);
var modelSetter = model.assign;
element.bind("change", function(e) {
scope.fileForImagepreview = (e.srcElement || e.target).files[0];
if (scope.fileForImagepreview.type === "image/jpeg" || scope.fileForImagepreview.type === "image/jpg" || scope.fileForImagepreview.type === "image/png") {
scope.$apply(function($scope) {
modelSetter(scope, element[0].files[0]);
});
};
var promise = fileReader.readAsDataURL(scope.fileForImagepreview, scope)
promise.then(function(result) {
scope.imageSrcForPreview = result;
});
});
}
};
};
和service包含此功能。
this.readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = this.getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};