我已经搜索过了,但没有得到准确的答案,是否可以直接将couchDB与angular.js框架连接起来。
或者
我们必须借助node.js来实现。
我已经搜索过了,但没有得到准确的答案,是否可以直接将couchDB与angular.js框架连接起来。
或者
我们必须借助node.js来实现。
Ashvin,感谢您的提问。我也在这个问题上遇到了困难。
我还没有找到如何使用$resource从AngularJS调用本地CouchDB的方法,因为它使用类似于完整的localhost URL:
http://localhost:5984/<dbname>/_all_docs
所有的AngularJS文档和示例都显示本地路径名。它们并没有真正告诉我们如何访问一个独立的Web服务,或者至少我没有找到一个有用的解释 :)
以下是一种使用jQuery更容易理解的方法。 我将其放在一个名为couch.js的文件中 - 以连接到我们的动物(狗,猫等)的CouchDB。 实际的模块(“app”)在应用程序的其他位置定义,因此我只是将其放在名为“app”的变量中,并添加了一个Couch控制器,如下所示:
(function () {
'use strict';
var app = angular.module('app');
app.controller('CouchCtrl', function ($scope,$http,$resource) {
var all_critters = 'http://localhost:5984/critters/_all_docs?callback=?';
$.getJSON(all_critters, function(json) {
$scope.$apply(function(){
$scope.all_critters = json;
});
});
$scope.getAllCritters = function() {
return $scope.all_critters;
};
});
}());
我在本地工作时为了避免浏览器的本地安全问题,添加了JSONP的?callback=?,因此我在CouchDB首选项中设置了JSONP = true。
在html页面中,只需将crittersDB绑定到调用结果即可:
<ul ng-controller="CouchCtrl">
<h5>Critters</h5>
<p>There are currently {{all_critters.total_rows}} critters.</p>
<li ng-repeat="(key,value) in all_critters">
{{key}} - {{value}}
</li>
</ul>
$scope.projects = ProjectCouch.get({q:'_all_docs', include_docs: 'true', limit: 10});
angular.module('CouchDB', ['ngResource']).
factory('ProjectCouch', function($resource) {
var ProjectCouch = $resource(':protocol//:server/:db/:q/:r/:s/:t',
{protocol: 'http:', server: 'localhost:5984', db:'projects'}, {update: {method:'PUT'}
}
);
ProjectCouch.prototype.update = function(cb) {
return ProjectCouch.update({q: this._id},
this, cb);
};
ProjectCouch.prototype.destroy = function(cb) {
return ProjectCouch.remove({q: this._id, rev: this._rev}, cb);
};
return ProjectCouch;
});