2

I have the following code to load a random line as required from a text file:

$.get('txt/messages.txt', function(txt) {
var lines = txt.responseText.split("\n");
var randLineNum = Math.floor(Math.random() * lines.length);
save(lines[randLineNum]); // random line from the text file
});

How could I do the same with Angular, to place the value into a scope value instead?

Poiro
  • 951
  • 4
  • 10
  • 20
  • 1
    There are no shortage of guides to making HTTP requests and putting data into the scope variable out there … and you already have the code to pick a random line… so what's the problem? – Quentin Feb 22 '16 at 14:42

1 Answers1

1

I can provide you Pseudocode. However, there are list of things when accessing file.If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:

http://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy.

Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).

Also, refer: AngularJS: factory $http.get JSON file for more details.

In your case, you would want to either write the code in a factory and get the data in return and assign it to a scope variable or simply write the code in the controller and assign the value to the variable you want.

myApp.controller("fileController", function($scope, $http) {
$http.get('txt/messages.txt').success(function(data) { 
    var lines = txt.responseText.split("\n");
    var randLineNum = Math.floor(Math.random() * lines.length);
    $scope.varYouWant = randLineNum;
});
Community
  • 1
  • 1
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46