我有一个处理文件上传的指令。该指令将'controller'和'controllerAs'用于动态控制器,并在'link'函数中触发在相关动态控制器中执行的回调。
的问题是当回调在控制器执行时,“这个”未定义。如何在控制器中设置imageUrl?
指示:
.directive('attachable', function(FileUploader) {
return {
restrict : 'E',
transclude : true,
templateUrl : 'template.html',
scope : {},
controller : '@',
controllerAs: 'uploadCtrl',
name : 'controller',
link: function(scope, element, attrs) {
var controller = scope.uploadCtrl;
var uploader = scope.uploader = new FileUploader({
url: controller.uploadUrl
});
// callbacks
uploader.onAfterAddingFile = function(item) {
controller.onAfterAddSuccess();
};
}
};
});
控制器:
angular.module('core').controller('controller', ['$window', function($window){
this.onAfterAddSuccess = function(item){
if ($window.FileReader) {
var fileReader = new FileReader();
fileReader.readAsDataURL(item._file);
fileReader.onload = function (fileReaderEvent) {
$timeout(function () {
this.imageURL = fileReaderEvent.target.result; // <- this is undefined
}, 0);
};
}
};
}]);
的HTML:
<attachable controller="controller" ></attachable>
编辑:
ste2425的答案解决了“未定义”错误,但是为什么在我的控制器(即视图)之外无法使用imageURL的新值?
更新的控制器:
...
fileReader.onload = function (fileReaderEvent) {
this.imageURL = '';
$timeout(function(){
this.imageURL = fileReaderEvent.target.result;
}.bind(this), 1);
};
...
的HTML:
imageURL: {{ imageURL }} <- this is still ''
<attachable controller="controller" ></attachable>
Angular会将this
of$timeout
设置为窗口。
您有几种选择。任何一个:
绑定函数的以下上下文:
this.test = 'hiya';
$timeout(function(){
console.log('this WONT fail', this.test);
}.bind(this), 1);
或正在使用角度v1.4.1或更高版本
$timeout(function(ctx){
console.log('this WONT fail', ctx.test);
}, 1, true, this);
看到小提琴:http : //jsfiddle.net/wopx3rtc/1/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句