一般来说,我才刚刚开始使用 Angular 和编码,所以请多多包涵...
我目前正在尝试编写一个类似于电话簿的基本 CRUD 应用程序。到目前为止,我在添加和查看联系人方面没有遇到任何问题,但我一直在研究如何通过 $http.put
和 MongoLab 的 API 在 MongoLab 上更新我的模型
任何正确方向的帮助或指示将不胜感激!
这是我的 UpdateCtrl 函数和附加的相关表格(为了演示目的,在此处放置了一个通用 URL):
Controller .js
function UpdateCtrl($scope, $http, $routeParams, $location){
$scope.contactId = $routeParams.contactId;
var url = 'https://api.mongolab.com/api/databases/<d>/collections/<c>/<id>;
$http.get(url).
success(function(mongoDataById) {
$scope.contact = mongoDataById;
});
$scope.updateContact = function() {
$http.put(url, $scope.contact);
};
}
update.html(局部 View )
<form ng-submit="updateContact()">
<label for="fullname">Name</label>
<input type="text" id="fullname" ng-model="contact.fullname" ><br/>
<label for="email">Email</label>
<input type="text" id="email" ng-model="contact.email"><br/>
<label for="phone">Phone</label>
<input type="text" id="phone" ng-model="contact.phone"><br/>
<button type="submit">Update</button>
</form>
编辑
@Stewie 和@Arun P Johny,当我执行 updateContact() 时,控制台中似乎没有任何错误。我怀疑它正在发送一个 PUT 请求,其中包含与初始 GET 请求相同的数据,即使在当前 $scope 的表单中进行了更改。 (是的,我的 Url 中有一个特定的 contactId - 在浏览器中进行了测试,它会提取我选择的特定联系人的数据)
@pkozlowski.opensource - 是的,我在开始这个项目时实际上添加了该库,但是当我能够使用相当简单的 $http POST 和 GET 函数时,我觉得没有必要。如果我不知道如何使用基本的 $http.put,现在可以试一试。
最佳答案
您可能需要 API key 才能访问 Mongo Lab 的 RESTful API,例如:
GET /databases/{database}/collections/{collection}
示例列出给定集合中的所有文档:
https://api.mongolab.com/api/1/databases/my-db/collections/my-coll?apiKey=myAPIKey
可选参数 [q=][&c=true][&f=][&fo=true][&s=][&sk=][&l=]
更多信息请访问: http://docs.mongolab.com/restapi/#authentication
如果您能告诉我们 Get 命令是否正常工作,那就太好了
关于http - angularjs + mongolab $http.put 不更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15403501/