3

I have a messaging "app" and I need to get the ID when a message is created. Here is all of the code below:

<html ng-app="sampleApp">

<body ng-controller="SampleCtrl">
    <ul>
        <li ng-repeat="message in messages">
            <input ng-model="message.message" ng-change="messages.$save(message)" />
            <input ng-model="message.by" ng-change="messages.$save(message)" />
            <button ng-click="messages.$remove(message)">Delete Message</button>
        </li>
    </ul>
    <form ng-submit="addMessage()">
        <input ng-model="newMessageText" />
        <input ng-model="newMessageBy" />
        <button type="submit">Add Message</button>
    </form>

    <!-- Angular -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

    <!-- Firebase -->
    <script src="https://www.gstatic.com/firebasejs/3.6.6/firebase.js"></script>

    <!-- AngularFire -->
    <script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
    <script>
        var config = {
            apiKey: "xxx",
            authDomain: "xxx",
            databaseURL: "xxx",
            projectId: "xxx",
            storageBucket: "xxx",
            messagingSenderId: "xxx"
        };
        firebase.initializeApp(config);
        var app = angular.module("sampleApp", ["firebase"]);
        app.controller("SampleCtrl", function ($scope, $firebaseArray) {
            var ref = firebase.database().ref().child("messages");
            $scope.messages = $firebaseArray(ref);
            $scope.addMessage = function () {

                $scope.messages.$add({
                    message: $scope.newMessageText,
                    by: $scope.newMessageBy
                });
            };
        });
    </script>
</body>

</html>

When a message is sent, it creates a ID and the message content under it. So, I need to get the ID of the message sent, and write the ID to Firebase.

Here's what the database looks like:

{
  "messages" : {
    "-KrsHPUi7pIWTQ1qgO4q" : { // I NEED TO GET THIS
      "message": "blah blah blah...",
      "by": "john"
    }
  },
  "ids" : {
    "first": "-KrsHPUi7pIWTQ1qgO4q" // AND PUT IT HERE
}

1 Answers1

1

here how you can get the id

$scope.messages.$add({
                    message: $scope.newMessageText,
                    by: $scope.newMessageBy
                }).then(function(ref) {
                   var id = ref.key;
                  // do with the key what ever you want
})
mohamad rabee
  • 577
  • 1
  • 5
  • 14
  • one more question however, how would i get the ID everytime something is changed, or to delete the id when a message is deleted? – Jaymie Jackson Aug 19 '17 at 20:28
  • 1
    please see in the link how to write data to firebase without generating a key, here https://stackoverflow.com/questions/24560075/setting-your-own-key-when-adding-an-object-to-firebase-angularfire – mohamad rabee Aug 19 '17 at 23:27