2017-01-22 116 views
1

我有以下代码:AngularJS文件输入onchange事件到controllerAs

<input onchange="angular.element(this).scope().filesChanged(this)" fileInput="controlFormCtrl.formData.episodeFile"> 

选择的文件,将被传递到的范围,将是我以这种方式控制器内部访问:

var thisScope = this; 
    var rootScope = $root; 
    var ctrlScope = $scope; 
    ctrlScope.filesChanged = function(elm) { 
    thisScope.file = elm.files[0]; 
    } 

elm.files具有以下数据:

lastModified: 1485109128000 
lastModifiedDate: Sun Jan 22 2017 19:18:48 GMT+0100 (CET) 
name:"border-image.png" 
size:1353 
type:"image/png" 
webkitRelativePath:"" 
__proto__: File 

然而thisScope.file不作为S等。

我能做些什么来解决这个问题?

+0

ctrlScope.file代替thisScope.file会的工作,但我使用'controllerAs',因为我有下海誓山盟嵌套多个控制器。 – Coder

+2

我的猜测是你需要运行'ctrlScope。$ apply();'让角度知道'thisScope'已经改变了。 –

+0

@RaphaelRafatpanah好的声音,因为必须使用'onchange'而不是'ng-change'(这种输入不支持),Angular不会运行$ digest循环。 –

回答

1

您需要运行ctrlScope.$apply();才能让角度知道thisScope已更改,但是,应该只在FileReader加载文件后运行。

我建议使用ngf-select指令来处理文件上传。

https://github.com/danialfarid/ng-file-upload