这种事情是行不通的。您尝试写入的文件将在服务器上;就像现在一样,它将是一个静态资源。我建议阅读 Angular 资源,here。您可以设置服务器端代码以对 json 文件执行 CRUD 操作,但最好使用实际数据库。如果您更喜欢使用 json 格式,Mongodb 是您的最佳选择; here 是 Mongodb 大学的链接,提供免费课程。我过去做过,效果很好。
现在,对于您的情况有一些实际帮助:
您可以对 json 文件执行 GET 请求,因为它被视为静态资源。然而,POST 请求需要服务器端脚本来执行任何操作。
$http.get('api/YOUR_RESOURCE').success(function(data) {
$scope.database = data;
});
$http.post('api/YOUR_RESOURCE', {
data_key: data_value,
data_key2: data_value2
}).success(function(data) {
data[id].available = false;
});
这可能会在您学习 Angular 的道路上走得更远,但这里是 Node.js 服务器代码的 sn-p,带有 Mongo 数据库和 Mongoose 来处理“架构”,以帮助您了解如何这行得通:
var mongoose = require('mongoose'),
YOUR_RESOURCE = mongoose.model('YOUR_RESOURCE');
app.route('/api/YOUR_RESOURCE')
// This should be your GET request; 'api/
.get(
// Get all docs in resource
YOUR_RESOURCE.find().exec(function (err, data) {
if (err) {
return res.status(400).send({
message: SOME_ERROR_HANDLER
});
} else {
res.json(data); // return list of all docs found
}
});)
// Add new doc to database
.post(function (req, res) {
// The keys of the object sent from your Angular app should match
// those of the model
var your_resource = new YOUR_RESOURCE(req.body);
your_resource.save(function (err) {
if (err) {
return res.status(400).send({
message: SOME_ERROR_HANDLER
});
} else {
// returns newly created doc to Angular after successful save
res.json(your_resource);
}
});
);
Here 是一个 SO 页面,其中包含有关 Node 入门的资源列表;我推荐 Node,因为它易于使用,而且它是用 JS 编写的。 Mongo 大学的课程还包括设置您的服务器以与数据库一起使用;您可以在多种风格之间进行选择,例如 Java、.NET、Python 或 Node。
上面的示例中遗漏了一些内容,例如 Mongoose 模型和节点设置,但如果您选择阅读它们,这些内容将包含在我在页面上链接到的资源中。希望这会有所帮助:)