【问题标题】:Storing Comments in firebase using angularjs使用angularjs在firebase中存储评论
【发布时间】:2014-07-15 00:45:52
【问题描述】:

这是一个表格:

<span class="input-label">Name</span>
<input ng-model="name" type="text">
<span class="input-label">Comment</span>
<input ng-model="msg" type="text">
<button ng-click="addMessage()">Comment</button>

在触发点击事件时,我在控制器中调用 addMessage() 函数:

app.controller('CommentCtrl', ['$scope', '$firebase', function($scope, $firebase){
    var myRootRef = new Firebase("my://app/link");
    $scope.addMessage = function() {
        /*
         * How do I store the name and comment obtained
         * from the form in firebase.
         *
         * set, push does not work at all
        */
        $scope.modal.hide();
    }
}]);

【问题讨论】:

    标签: javascript database angularjs firebase angularfire


    【解决方案1】:

    你真的很接近,只是几件事。

    我们需要通过传入 Firebase 引用来创建 AngularFire 绑定。由于我们使用的是ng-model,我们可以从$scope 获取属性。但是,为 name 和 comment 属性提供默认值可能是个好主意。

    当我们调用addMessage 时,我们需要通过调用$child 前往子位置获取消息。然后我们可以通过调用$add添加一条新消息。

    Plunker Demo

    app.controller('CommentCtrl', ['$scope', '$firebase', function($scope, $firebase){
        var myRootRef = new Firebase("my://app/link");
        $scope.messages = $firebase(myRootRef); // AngularFire binding created here
    
        // default values
        $scope.name = '';
        $scope.msg= '';
    
        $scope.addMessage = function() {
            // go to the messages location and push the item by calling $add
            $scope.messages.$child('messages').$add({
              name: $scope.name,
              comment: $scope.msg
            });
    
            // clear out the values after adding them to Firebase
            $scope.msg= '';
            $scope.name = '';
    
            $scope.modal.hide();
        }
    }]);
    

    【讨论】:

    • 我试过了。但是firebase数据库中的值只是一个空字符串
    • 真的越来越难了。
    • 啊,那是因为我在 $scope 上错误地命名了您的评论属性。它应该是味精而不是评论。由于 ng-model 设置为 msg 并且 comment 设置为空字符串,它永远不会被更新。所以我们可以把评论改成味精。现在就试试。同时让我知道您输入的值是什么。
    • 我试过了,实际上我第一次注意到它,但它仍然是空字符串。值只是名称和评论的胡言乱语
    • 它仍然为空。不知道为什么 $scope.name 为空 :(
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2017-05-30
    • 1970-01-01
    • 2013-08-26
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多