-1

I would like to allow user upload a JSON file and assign the content of the JSON file to a $scope variable.

After the content of the file is been assigned to the scope variable, I want to totally discard the file itself and not storing it anywhere.

How to efficiently implement this function?

1
  • Have you tried anything so far? Do you have any code involving the import of the JSON file and you're just looking for help parsing the file into your scope variable? Because it seems like you have things planned out well so I don't know what you're looking for here. How to ask a question on Stack Overflow Commented May 4, 2016 at 22:55

1 Answer 1

1

In your template:

<input type="file" onchange="angular.element(this).scope().onFileChange(this)">

In your JS:

$scope.onFileChange = function (fileEl) {
  var files = fileEl.files;
  var file = files[0];
  var reader = new FileReader();

  reader.onloadend = function(evt) {
    if (evt.target.readyState === FileReader.DONE) {
      $scope.$apply(function () {
        $scope.something = JSON.parse(evt.target.result);
      });
    }
  };

  reader.readAsText(file);
};

"onchange" instead of "ng-change", because it looks like Angular doesn't support binding things with ng-change on file upload input controls.

This was stolen almost verbatim from a co-worker's code. It might be Chrome-specific. If someone who knows me sees this, all credit is due to this coworker. And it's all due to him in any event anyhow. ;)

Sign up to request clarification or add additional context in comments.

3 Comments

The file is never transferred over the web nor stored anywhere in this example.
Correct. Input type file doesn't support ngModel.
If you happen to turn off the debug info in Angular (see docs.angularjs.org/guide/production), the ".scope()" in that onchange request won't work. But few people seem do that (in our app we saw pretty much no change in perf and it just made on the fly debugging more difficult--so we left it on).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.