AngularFire:如何将数据绑定到 $scope?

AngularFire: How to bind data to the $scope?

我正在尝试学习 Firebase,发现 MongoDB 和 Firebase 不同。 :-)

要制作一个简单的 "Likes" 计数器,在视图中我有:

<span>Likes: {{post.likes}}</span>
<form ng-submit="upLike(post)">
  <input type="submit" value="Up"></input>
</form>

在 MongoDB 这个控制器工作:

$scope.upLike = function(post) {
  console.log("Liked!");
  var likes = post.likes || 0;
  post.likes += 1;
  $http.put('http://localhost:8080/api/blogDB/' + post._id, post).then(function(response) { // UPDATE
    console.log("Upliked.");
  }, function(response) {
    console.log("Invalid URL");
  });
}

$scope.posts 是一个数组。 post 是数组中的一个对象。 MongoDB 从对象 (post) 中提取 _id,然后用新数据更新集合 (posts) 中的记录。

使用 Firebase 我做不到 $http.put。相反,我必须将新数据绑定到 $scope,它会绑定到 Firebase。

app.controller('ShowController', ['$scope', '$firebaseArray',
function($scope, $firebaseArray) {

  var ref = new Firebase("https://my-firebase.firebaseio.com/");
  $scope.posts = $firebaseArray(ref);

  $scope.upLike = function(post) {
    console.log("Liked!");
    var likes = post.likes || 0;
    post.likes += 1;
    // What goes here instead of $http.put?
  }

$scope.post.likes += 1; 不起作用,因为 post 不是 $scope.

上的数组

$scope.posts.likes += 1; 不起作用,因为我无法确定哪个 post 获得了赞。

我应该使用 ng-click 而不是 ng-submit 吗?我可以使视图增量喜欢,但我不知道如何将此数据附加到 $scope。我应该用 ng-model 做些什么吗?

我相信你要调用的 $scope.upLike 函数 $firebaseArray.$save(recordOrIndex):

$scope.upLike = function(post) {
    post.likes += 1;
    $scope.posts.$save(post);
};

如果您使用的是 $firebaseObject,那么您会调用 object.$save()

编辑:是的,您可能还应该使用 ng-click 而不是 ng-submit。当您一次收集多个输入时,或者当您想要利用 Angular 的表单验证时,您才真正需要一个表单。否则一个按钮就可以了。