我试图找出如何在AngularJS中使用PouchDB。我试图按照这些说明https://github.com/wspringer/angular-pouchdb
我认为我在理解创建工厂和/或服务的语法时遇到了问题。我得到了"与数据库交互"
的部分app.js
'use strict';
angular
.module('myappApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'pouchdb'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
angular.factory('someservice', function(pouchdb) {
// Do something with pouchdb.
var db = pouchdb.create('testdb');
pouchdb.destroy('testdb');
db.put({_id: 'foo', name: 'bar'});
});
当我添加" db.put"时,我在浏览器控制台中看到的消息是:
[15:17:45.343] TypeError: angular.factory is not a function @ http://127.0.0.1:9000/scripts/app.js:21
答案 0 :(得分:2)
angular
对象没有工厂方法,因此它将作为未定义返回。
尝试将它放在模块方法返回的对象上。
angular
.module('myappApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'pouchdb'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
// note the difference here, it is using the object returned by module() and config()
.factory('someservice', function(pouchdb) {
// Do something with pouchdb.
var db = pouchdb.create('testdb');
pouchdb.destroy('testdb');
db.put({_id: 'foo', name: 'bar'});
});
答案 1 :(得分:0)
此外,我能够调整此代码示例来测试数据库是否正常工作 http://plnkr.co/edit/M2K7no75zonXKcXKF9Sc?p=preview
app.js '使用严格的';
angular
.module('myappApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'pouchdb'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.factory('MyModel', function(pouchdb) {
return new pouchdb.create('mydb');
})
.run(function (){
var db = new PouchDB('mydb');
db.info().then(function(info) {
if (info.doc_count < 2) {
db.post({display: 'Hello'});
db.post({display: 'World'});
}
});
});
main.js
'use strict';
angular.module('myappApp')
.controller('MainCtrl', function ($scope, MyModel) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
MyModel.info().then(function(info) {
$scope.numOfDocs = info.doc_count;
});
$scope.options = {
db: MyModel,
name: 'Visitor'
};
$scope.db = MyModel;
});
main.html中
<p>Hello {{options.name}}! There are {{numOfDocs}} docs in your Pouch</p>
<p>Root scope:</p>
<ul>
<li pouch-repeat="item in db" ng-bind="item.display"></li>
</ul>
<p>Child scope:</p>
<ul>
<li pouch-repeat="item in options.db" ng-bind="item.display"></li>
</ul>