angularjs - 'this' is undefined in callback from directive -


i have directive handles file uploads. directive uses 'controller' , 'controlleras' dynamic controllers , in 'link' function fires callbacks gets executed in relevant dynamic controller.

the problem when callback executed in controller, 'this' undefined. how set imageurl in controller?

directive:

.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();       };    }   }; }); 

controller:

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;  // <- undefined                 }, 0);             };         }     }; }]);         

html:

<attachable controller="controller" ></attachable>   

edit:

ste2425's answer resolves 'undefined' error why imageurl's new value not available outside controller i.e. view?

updated controller:

... filereader.onload = function (filereaderevent) {      this.imageurl = '';     $timeout(function(){         this.imageurl = filereaderevent.target.result;     }.bind(this), 1); }; ... 

html:

imageurl: {{ imageurl }}     <- still '' <attachable controller="controller" ></attachable>   

angular set this of $timeout window.

you have couple of options available. either:

bind context of function:

    this.test = 'hiya';     $timeout(function(){         console.log('this wont fail', this.test);     }.bind(this), 1); 

or using angular v1.4.1 or higher

   $timeout(function(ctx){         console.log('this wont fail', ctx.test);     }, 1, true, this); 

see fiddle: http://jsfiddle.net/wopx3rtc/1/


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -