firebase中

时间:2016-07-19 16:10:18

标签: javascript angularjs firebase firebase-realtime-database

我是firebase的新手,我不确定我是否正确存储数据。

我正在构建一个表单来存储数据。现在它只有2个字段,但是我稍后会添加一些输入字段。

我的表单HTML如下所示:

<form>
<div class="form-group">
    <input placeholder="Event Title..." class="form-control" name="eventTitle" ng-model="newEvent.title">
</div>
<div class="form-group">
    <input placeholder="random..." class="form-control" name="eventRandom" ng-model="newEvent.random">
</div>
<button type="submit" class="btn btn-primary pull-right" ng-click="addEvent(newEvent);newEvent = null;">send</button>

我的控制器看起来像这样:

.controller('ChatCtrl', function ($scope, Ref, $firebaseArray, $timeout) {
// synchronize a read-only, synchronized array of events, limit to most recent 10
$scope.events = $firebaseArray(Ref.child('events').limitToLast(10));

// display any errors
$scope.events.$loaded().catch(alert);

// provide a method for adding a event
$scope.addEvent = function(newEvent) {
  if( newEvent ) {
    console.dir('newEvent: '+ newEvent);
    // push a event to the end of the array
    $scope.events.$add({newEvent})
      // display any errors
      .catch(alert);
  }
};

在firebase中,数据如下所示:

enter image description here

&#34; newEvent&#34;节点似乎完全多余。我不确定如何正确编码我的表单和控制器。我似乎在互联网上找到的所有示例都使用聊天室作为示例,发送表单只包含一个textarea字段。

我确实找到了一个包含多个字段的示例,它显示了上面的示例,但正如我所指出的那样,&#34; newEvent&#34;在firebase生成密钥后,节点似乎是多余的。

使用多个输入字段对表单进行编码的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

如果你想摆脱newEvent并纯粹设置结构:

events
    push-key
        random: "random",
        title: "event title"
    push-key
        ...

更改$add数据的方式:

$scope.events.$add({ title: newEvent.title, random: newEvent.random })
// display any errors
.catch(alert);

您正在推送具有以下结构的对象:

newEvent
    random: "random",
    title: "event title"

将在推键下插入整个对象。