Skyzer
Skyzer

Reputation: 592

Get contents of child_added while watching firebaseArray

I have a simple private chat, but with different type of messages, so when i send to server json structure I pass message type too.

$scope.messages = fireChat.firebaseArray;
$scope.addMessage = function(e) {

    //ADD TO FIREBASE
    $scope.messages.$add({
        uid: $scope.authData.uid,
        text: $scope.msg,
        timestamp: Firebase.ServerValue.TIMESTAMP,
        type: 'msg'
    });

    $scope.msg = ""; //RESET MESSAGE

};

As you can see there is property 'type'.

Now i'd like to watch for any new messages. As in documentation there is a watch API function, but it only returns the ID of the record/message. I'd like to get the contents of the message and check what is type is there and then according to that run other js functions.

$scope.messages.$watch(function (data) {
    console.log("angularfire watch");
    console.log(data);
    console.log(data.event);
    console.log(data.key);
    console.log(data.prevChild);
});

Above would return only child_added -Jp6KZWlyDtDETz8Agpr and -Jp6KZWlyDtDETz8ospr. As you see, no body under the key
Is there a possibility to get a the key contents? So I could do for example

switch (key.type) {
  case 'paid':
    animate_paid();
}

Edit:

$scope.messages.$watch(function (data) {
    console.log("angularfire watch");
    console.log(data);
    console.log(data.event);
    console.log(data.key);
    console.log($scope.messages.$getRecord(data.key));
});

The above code works finally

Upvotes: 0

Views: 811

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You can use the $getRecord to do it:

console.log($scope.messages.$getRecord(data.key));

You can look through the api for arrays here: https://www.firebase.com/docs/web/libraries/angular/guide/synchronized-arrays.html

Upvotes: 1

Related Questions