我对 Angular 比较陌生,并且仍在尝试围绕它的所有魔力和范围进行思考。
我正在尝试使用预览脚本进行简单的图像上传,但我错过了最后一块。
我已经设法分别完成了每个任务(上传和预览),但我坚持将其拼凑在一起。
这是我到目前为止的代码:
爪哇语
angular.module('fileUpload', [])
.controller("upload", ['$scope', '$http', function($scope, $http) {
$scope.$watch('file', function(file) {
console.log("arguments", file);
// Upload file via $http, formdata & transformRequest
});
}])
.directive("fileinput", [function() {
return {
scope: {
fileinput: "="
},
link: function(scope, element, attributes) {
element.bind("change", function(changeEvent) {
scope.fileinput = changeEvent.target.files[0]; // Trigger $watch in controller
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
// Should add the base64 for my filepreview variable
scope.filepreview = loadEvent.target.result;
});
}
reader.readAsDataURL(scope.fileinput);
});
}
}
}]);
.HTML
<input type="file" fileinput="file" />
<img ng-src="{{filepreview}}" class="image"/>
因此,正如您可能看到的,我将指令中的 fileinput 绑定到控制器中的 $scope.file。它有效。当触发文件输入的更改时,控制器中的文件变量正在获取正确的数据,以便我发送和上传它。我现在的问题是,我正在使用指令中的 fileinput 来调用FileReader
,运行readAsDataURL
,然后在完成后侦听,将其应用于范围,在这里我停止。我想更新变量filepreview
以便它在模板中更新(请参阅 HTML 和 IMG),但我根本无法弄清楚如何连接两者。文件预览不应保存,而仅用于向用户显示他们刚刚选择的图像。
因此,从本质上讲,我想将scope.filepreview
与控制器等filepreview
绑定。
我该怎么做呢?
谢谢
fileinput
指令使用隔离作用域,需要将其更改为继承作用域或将filepreview
作为属性传递
使用隔离范围:
<input type="file" fileinput="file" filepreview="filepreview"/>
指令隔离范围:
scope: {
fileinput: "="
filepreview: "="
},
设置文件预览内部指令
scope.filepreview = loadEvent.target.result;