2

AngularJS $scope.model is undefined when I initialize it via Javascript

<button ngf-select="upload($file)">Выбрать</button>
                <span id="photoSpan"></span>
                <input type="text"  id="photo" name="uploadPhoto" ng-model="uploadPhoto">

Here is my initialization code:

document.getElementById("photo").value = fileName;
                $("#photoSpan").text(resp.config.data.file.name);
                console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);

So

createExpositionResource.photo = $scope.uploadPhoto;
        console.log('--------------'+$scope.uploadPhoto);

returns undefined.

What am I doing wrong?

Thank you!

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Sanat Serikuly
  • 189
  • 3
  • 16

1 Answers1

6

What am I doing wrong?

Using Jquery: Have a look at this question: "Thinking in AngularJS" if I have a jQuery background?

You should replace

document.getElementById("photo").value = fileName;

by

$scope.uploadPhoto = fileName;

Short explanation : If you update an angular variable (eg : document.getElementById("photo").value = fileName;), angular won't know that you did it. There is worse with your code. For Angular, what's in $scope is his "trusted data source". Which means that Angular could also erase the value you put by using Jquery.

Community
  • 1
  • 1
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66