1

As far as I know, AngularJS applications are supposed to be single-page. That also should be true for web forms.

I can easily process a text input field:

var app = angular.module('snippet', []);

app.controller('MainCtrl', function($scope) {
  $scope.submit = () => {
    $scope.result = $scope.inputText;
  }
});
h1 {
  font-family:Arial;
  font-size:14pt;
}
<!DOCTYPE html>
<html ng-app="snippet">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS snippet</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div>
      <h1>Enter text:</h1>
      <input ng-model="inputText">
      <input type="button" ng-click="submit()" value="submit">
    </div>    
    <div>
      <h1>Text you have entered:</h1>
      <span>{{result}}</span>
    </div>
  </body>
</html>

However, when I change input type="text" to input type="file" and try to specify a text file, the $scope.result property remains undefined:

var app = angular.module('snippet', []);

app.controller('MainCtrl', function($scope) {
  $scope.submit = () => {
    $scope.result = $scope.inputFile;
  }
});
h1 {
  font-family:Arial;
  font-size:14pt;
}
<!DOCTYPE html>
<html ng-app="snippet">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS snippet</title>
    <link rel="stylesheet" href="style.css" />
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div>
      <h1>Enter text:</h1>
      <input type="file" accept=".txt" ng-model="inputFile">
      <input type="button" ng-click="submit()" value="submit">
    </div>
    
    <div>
      <h1>Text you have entered:</h1>
      <span>{{result}}</span>
    </div>
  </body>

</html>

How should I modify the snippet above to make it works with a text file?

enkryptor
  • 1,574
  • 1
  • 17
  • 27
  • it's not clear what you are trying to do. Are you expecting the browser to read the file and set the model to the text contained in the file? – Claies Aug 10 '16 at 13:13
  • @Claies basically, yes. I want to initialize the model property from a file, not from a text input field. – enkryptor Aug 10 '16 at 13:14
  • files are *binary*. in order to do this, you would have to read the file using the browser file api and convert it from binary to text. this isn't supported by `ng-model`. – Claies Aug 10 '16 at 13:19
  • @przno thank you! I wonder why I couldn't find that – enkryptor Aug 10 '16 at 13:22

0 Answers0