【发布时间】:2017-11-10 02:46:55
【问题描述】:
我正在使用 angularjs/javascript 代码进行图像上传,但我陷入了变量绑定,谁能帮助我,这是我的代码。
var image_source;
$scope.uploadedFile = function(element) {
reader.onload = function(event) {
image_source = event.target.result;
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
console.log(image_source,event.target.result, element.files[0], "***not working here***");
我在函数内绑定了名为image_source 的变量,但是当我在函数外访问它时,它总是返回未定义的为什么?
PS:- 我可以使用phatarrow operator 在打字稿中得到这个,但我不知道如何在 javascript 中做
【问题讨论】:
-
你在哪里声明了 image_source??
-
尝试在范围之外声明它
-
我已经在函数外声明了
-
文件操作是异步操作。您在 onload 方法中为
image_source赋值。这可能是不工作的原因 -
它的函数范围,不知道你为什么期望它可以在外部访问。 fat-arrow 函数获取父块的范围,因此它可能在 es6 中工作。你期待 es5 中的块作用域吗?那行不通。
标签: javascript angularjs