我已经开始使用AngularFire并遇到一些挑战,将数据输入我的Firebase应用程序。我正在使用AngularJS和AngularFire/Firebase的CDN。
JS:
var app = angular.module('VoteTrackerApp', ['firebase']);
app.constant('FIREBASE_URI', 'https://XXXXXXXXX.firebaseio.com/');
app.controller('VoteTrackerController', ['$scope', 'VoteTrackingService', function($scope, VoteTrackingService) {
'use strict';
$scope.vote = { name: '', tally: 0 };
$scope.addVotes = function() {
VoteTrackingService.addVotes($scope.vote);
$scope.vote = { name: '', tally: '' };
};
}]);
app.factory('VoteTrackingService', ['$firebase', 'FIREBASE_URI', function($firebase, FIREBASE_URI) {
'use strict';
var ref = new Firebase(FIREBASE_URI);
var votes = $firebase(ref);
return {
getVotes: function() {
return votes;
},
addVotes: function(vote) {
votes.$add(vote);
}
};
}]);
下面是HTML:
<div ng-app="VoteTrackerApp">
<div ng-controller="VoteTrackerController">
<form ng-submit="addVotes()">
Candidate: <input type="text" ng-model="vote.name" />
Number of Votes: <input type="text" ng-model="vote.tally" id="tally" /> <input type="submit" value="Add" />
</form>
<ul>
<li ng-repeat="(id, vote) in votes">
{{vote.name}} has {{vote.tally}} votes
</li>
</ul>
</div>
我的控制台显示这个错误:
TypeError: undefined is not a function
at Object.addVotes (http://localhost:9000/scripts/main.js:24:19)
at k.$scope.addVotes (http://localhost:9000/scripts/main.js:9:29)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:176:88
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:193:165
at k.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:111:373)
at k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:112:121)
at HTMLFormElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:193:147)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:31:161
at q (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:7:290)
at HTMLFormElement.c (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:31:143)
我感谢社区可以与我分享的任何见解。提前谢谢你。干杯!:)
在$firebase
ref上没有$add
方法。您需要在其上调用$asArray()
以获得同步对象。查看快速入门了解更多详细信息。
var votes = $firebase(ref).$asArray();
此外,您不需要包装数组。您可以简单地返回它并直接使用API:
app.factory('VoteTrackingService', ['$firebase', 'FIREBASE_URI', function($firebase, FIREBASE_URI) {
'use strict';
var ref = new Firebase(FIREBASE_URI);
return $firebase(ref).$asArray();
}]);
app.controller('VoteTrackerController', ['$scope', 'VoteTrackingService', function($scope, VoteTrackingService) {
$scope.vote = { name: '', tally: 0 };
var votes = VoteTrackingService;
votes.$add($scope.vote);
}]);