send variable from basic js to angular

82 views Asked by At

I want to send variable in basic JS to angular in function. I want to send variable value1. as you are seeing the code I declare value1 and after script is closed I want to send the value of value1 to the function doImportAll that declared in other file.

<script>
      var value1='hi';
      var openFile = function(event) {
          var input = event.target;

          var reader = new FileReader();
          reader.onload = function(){
              var text = reader.result;
              var node = document.getElementById('output');


              var lines = reader.result.split('\n');
              for(var line = 0; line < lines.length; line++){
                  console.log(lines[line]);
              }
              value1=lines[0];
              node.innerText = lines[2]
              document.getElementById('clicking').click();
          };
          reader.readAsText(input.files[0]);
      };
  </script>
  <button id="clicking"  class="btn btn-md" ng-click="doImportAll(value1)" my-i18n="modal_importAll"></button>
  <div>
      <input type='file' accept='text/plain' onchange="openFile(event)">
  </div>
  <div id='output'>
      ...
  </div>
2

There are 2 answers

0
Hayk Aghabekyan On

You can inject the value into your angular app and then use that

angular.module('App').value('yourVar', value);

angular.module('App').controller('Controller', function ($scope, yourVar) {
    console.log(yourVar);
});

Here is working example http://plnkr.co/edit/rUCXJ0GmEb5iWf8OiBs6?p=preview

0
Noam On

As already pointed out, there's no reason not to do this within an angular service. But if for whatever your reason you wish to have this function not run inside angular, you can assign value to the global window object like so:

window.value1 = lines[0];

It will then be accessible to the angular via the window object. This is not the most elegant solution and you should really consider restructuring your FileReader logic to work within angular.