0

i'm using angularJs 1.7 components.

This is my component who uploads a picture then converts it to base 64, then it is supposed to display it, but the displaying doesnt work .

myApp.component('club', {
  templateUrl: 'vues/club.html',
  controller: function($log,$scope) {

        // HTML form data, 2 way binding ..
        this.club = {};


        // Bse 64 encoder
        encodeImageFileAsURL = function() {

                var filesSelected = document.getElementById("inputFileToLoad").files;
                if (filesSelected.length > 0) {
                  var fileToLoad = filesSelected[0];

                  var fileReader = new FileReader();

                  fileReader.onload = function(fileLoadedEvent) {

                        var srcData = fileLoadedEvent.target.result; // <--- data: convert base64 : OK

                        this.club.img = srcData ; // Displaying in view doesnt work 
                }
                  fileReader.readAsDataURL(fileToLoad);
                }
              }


            // Jquery watcher when we upload a picture
            $(document).on('change', 'input[type="file"]' , function(){
                encodeImageFileAsURL();
            });

This is the html button inside the template :

<div id="upload_button">
        <label>
            <input name="inputFileToLoad" id="inputFileToLoad" ng-model="logo"  type="file"  onchange=""  /> </input>
            <span class="btn btn-primary">Upload picture</span>
        </label>
  </div>

This is the error :

TypeError: this.club is undefined

srcData is ok, and holds a base 64 image, the function works well.

I've tried the solution provided (.bind(this)) there with no luck , i dont know where to place it:

How to access the correct `this` inside a callback?

When using the $scope syntax, it is working, adding $scope.$apply(), but now i'm using components based dev, and the .this syntax, it doesnt work any more .

EDIT 1 : Ok, i've initialized club with

$scope.club = {} ;

then inside the function, i'm writing

$scope.club.img = srcData ;

Then, it is working ok. I dont understand why .this is not the same than $scope !

harmonius cool
  • 337
  • 1
  • 2
  • 23

1 Answers1

0

See following example for where this object has reference to

a={
  firstname:"something",
  lastname:"something2",
  fullname:function(){
      console.log(this.firstname+' '+this.lastname);
  }
}

a.fullname();

In above example Object a is created and inside fullname() function this object pointing to 'a' Object.

So that in your case templateUrl is only variable on this Object if you do not want to use $scope. You can declare it by using var club = {}

Nikhil Lende
  • 129
  • 7