0

I'm attempting to create a simple guestbook with AngularJS, and read and write the names to a simple file. Trouble is, I can't seem to get my code to even read from the file.

This is my directory structure:

Directory Structure

This is index.html:

<!DOCTYPE html>
<html ng-app>
    <head>
        <meta charset="ISO-8859-1">
        <title>GuestBook</title>
        <script src="http://code.angularjs.org/angular-1.0.0rc3.min.js"></script>
        <script type="text/javascript" src="javascript/user.js"></script>
    </head>
    <body>
        <h1>Welcome!</h1>
        <div ng-controller="UserCtrl">
            <ul class="unstyled">
                <li ng-repeat="user in users">
                    {{user}}
                </li>
            </ul>
        </div>
    </body>
</html>

This is user.js (Based off this question/answer):

function UserCtrl($scope) {

    $scope.users = $(function() {
        $.get('data/users', function(data) {
            var array = data.split(',');
            console.log(array);
        });
    });
}

And this is my users file:

John,Jacob,James

I'm expecting this outcome:

Welcome!

  • John
  • Jacob
  • James

But instead, all I get is:

Welcome!

So my question is, how can I populate $scope.users with the names in the users file?

I know I've got my AngularJS set up correctly because I was able to get the desired result when I hard-coded it:

$scope.users =[John,Jacob,James];

I've also spent a lot of time googling and searching Stack Overflow for how to read and write to a file with JavaScript and/or AngularJS, but:

  1. No one seems to be trying to do exactly what I'm trying to do;
  2. The instructions are either confusing or not really applicable to what I'm trying to do.

I'm also not sure where to begin to write code that will persist names to the users file -- but I'll be happy if I can just read the file for now, and ask how to write to it later in a separate question. (But extra gratitude if you do also show me how to write to it.)

4 Answers 4

4

Try injecting angular's $http service into your controller first of all. And make sure you add a '/' before your 'data/users' path. (/data/users)

function UserCtrl($scope, $http) {
    $scope.users = [];
    $http.get('/data/users')
        .success(function(data, status, headers, config) {
            if (data && status === 200) {
                $scope.users = data.split(',');
                console.log($scope.users);
            }
        });
    });
}

You can check your console to see what kind of data is being returned. (Network tab)

edit: just realized the $(function ... part didn't make sense.

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

3 Comments

Hmmm... Still not working. After $scope.users = [] I put alert("first"), and after $http.get... I put alert("second"). I only got the first alert. Am I missing something?
Does your console.log even run? Or does it fail on the request?
That part of the code never even runs. I put alert("second") right above the if statement, and nothing happened.
2

The problem with your code is in this stub -

$scope.users = $(function() {
    $.get('data/users', function(data) {
        var array = data.split(',');
        console.log(array);
    });
});

Here $scope.users is not the array variable. Instead, it is whatever $() returns. Your anonymous function is passed only as a parameter to $ function.

Rewrite your controller this way -

function UserCtrl($scope, $http) {
    $scope.users = [] // Initialize with an empty array

    $http.get('data/users').success(function(data, status, headers, config) {
        // When the request is successful, add value to $scope.users
        $scope.users = data.split(',')
    })
}

And now, since you have

<li ng-repeat="user in users">
    {{user}}
</li>

in your view, angular will set up a watch on $scope.users variable. If the value of $scope.users changes anytime in the future, angular will automatically update the view.

EDIT -

Along with the above edit, you need to make sure all the files are being served via a web server on the same host:port. Browsers limit AJAX access to another domain:port. Here is a quick way to do start a http server -

Go to the project directory using terminal and type in

python -m SimpleHTTPServer for python

or

ruby -run -e httpd -- -p 8000 . for ruby.

Both will start a basic HTTP server at port 8000, serving content from that particular directory. Having done this, your index.html will be at http://localhost:8000/index.html and your data file should be accessibe as http://localhost:8000/data/user.js (your javascript can still use /data/user.js).

11 Comments

Hmmm... Still not working. After $scope.users = [] I put alert("first"), and after $http.get... I put alert("second"). I only got the first alert. Am I missing something?
Can you check your path? Should you be using /data/users instead of data/users?
If the data/users is accessible, try adding alert(JSON.stringify(data)) just before $scope.users = data.split(',').
I meant to say, I put alert("second") inside of (not after). In other words, I did this: $http.get('/data/users').success(function(data, status, headers, config) { alert("second"); but it never gave the second alert.
No. If you are accessing index.html without a web server (i.e, directly using file:///), it is not allowed. Browsers prevent loading content from different origin. If you check the web inspector in chrome, you'll get a Access-Control-Allow-Origin error (e.g. d.pr/i/BUC0)
|
0

It turns out I can't do what I'm trying to do the way I'm trying to do it. JavaScript by itself can't read files on the Server-Side, only on the Client-Side. To read and persist data, JavaScript has to make calls to a "Back-end" or server, written in something like Java, which isn't just a Browser scripting language.

Comments

0

you entered 'users' instead of 'users.txt' as filename.

This works just fine to me:

function UserCtrl($scope, $http) {
    $scope.users = []
    $http.get('data/users.txt').success(function(data, status, headers, config) {
        $scope.users = data.split(',')
    })}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.