读取和写入AngularJS中的服务器端文件 [英] Reading and writing to a server-side file in AngularJS
问题描述
我正在尝试使用AngularJS创建一个简单的留言簿,并将名称读写到一个简单的文件中。麻烦的是,我似乎无法让我的代码甚至从文件中读取。
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.
这是我的目录结构:
这是index.html:
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>
这是user.js(基于 这个问题/答案 ):
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);
});
});
}
这是我的用户档案:
John,Jacob,James
I期待这个结果:
- John
- 雅各布
- 詹姆斯
相反,我得到的只是:
所以我的问题是,我如何用名称填充$ scope.users用户文件?
So my question is, how can I populate $scope.users with the names in the users file?
我知道我的AngularJS设置正确,因为当我对其进行硬编码时,我能够得到所需的结果:
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];
我还花了很多时间在谷歌搜索和搜索Stack Overflow如何读取和写入一个包含JavaScript和/或AngularJS的文件,但是:
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:
- 似乎没有人试图做我正在尝试做的事情;
- 说明要么令人困惑,要么不适用于我正在尝试做的事情。
我也不知道从哪里开始编写将名称保存到用户文件的代码 - 但是如果我现在可以只读取该文件,我将很高兴,并在稍后的单独问题中询问如何写入该文件。 (但如果你也告诉我如何写它,还要感激。)
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.)
推荐答案
尝试将angular的$ http服务注入你的控制器首先。并确保在数据/用户路径之前添加/。 (/ data / users)
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.
这篇关于读取和写入AngularJS中的服务器端文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!