Reading and writing to a server-side file in AngularJS

和自甴很熟 提交于 2019-12-06 14:57:49

问题


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:

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.)


回答1:


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.




回答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).




回答3:


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.




回答4:


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(',')
    })}


来源:https://stackoverflow.com/questions/19299158/reading-and-writing-to-a-server-side-file-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!