Angularjs ';这';在从指令回调中未定义
我有一个处理文件上传的指令。该指令对动态控制器使用“controller”和“controllerAs”,并在“link”函数中触发在相关动态控制器中执行的回调 问题是在控制器中执行回调时,“this”未定义。如何在控制器中设置imageUrl 指令:Angularjs ';这';在从指令回调中未定义,angularjs,Angularjs,我有一个处理文件上传的指令。该指令对动态控制器使用“controller”和“controllerAs”,并在“link”函数中触发在相关动态控制器中执行的回调 问题是在控制器中执行回调时,“this”未定义。如何在控制器中设置imageUrl 指令: .directive('attachable', function(FileUploader) { return { restrict : 'E', transclude : true, templateUrl : 'temp
.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);
};
}
};
}]);
...
fileReader.onload = function (fileReaderEvent) {
this.imageURL = '';
$timeout(function(){
this.imageURL = fileReaderEvent.target.result;
}.bind(this), 1);
};
...
html:
imageURL:{{imageURL}Angular将$timeout
的this
设置到窗口
你有几个选择。要么:
将函数绑定到此函数的上下文:
this.test = 'hiya';
$timeout(function(){
console.log('this WONT fail', this.test);
}.bind(this), 1);
或者正在使用angular v1.4.1或更高版本
$timeout(function(ctx){
console.log('this WONT fail', ctx.test);
}, 1, true, this);
请参阅fiddle:这是JavaScript闭包的副作用。解决这个问题最常用、最直接的方法是声明一个表示控制器的常量变量,它可以在闭包内引用,而不会被闭包本身隐藏
angular.module('core').controller('controller', ['$window', function($window){
var vm=this; //constant reference to controller
....
fileReader.onload = function (fileReaderEvent) {
vm.imageURL = '';
$timeout(function(){
vm.imageURL = fileReaderEvent.target.result;
}, 0);
};
....
您的建议解决了“未定义”,但请检查我编辑的问题-imageURL的新值未反映在我的视图中。有什么建议吗?因为您使用的是this
和controllerAs
,您不需要在视图中使用uploadCtrl.imageURL
引用它吗?我从来没有在指令中这样做过,但它是如何与ng控制器一起工作的。如果要使用视图中的语法,请将控制器废弃为,并将此
替换为$scope
。
$timeout(function(ctx){
console.log('this WONT fail', ctx.test);
}, 1, true, this);
angular.module('core').controller('controller', ['$window', function($window){
var vm=this; //constant reference to controller
....
fileReader.onload = function (fileReaderEvent) {
vm.imageURL = '';
$timeout(function(){
vm.imageURL = fileReaderEvent.target.result;
}, 0);
};
....