angular $firebaseArrray: difference between controller and directive

132 views Asked by At

this is my first question on stack overflow, so please bear with me :-).

I have an angular app, where I would like to display user info, retrieved from firebase.

The funny thing is, I'm getting somewhat different data from firebase, when I'm making the firebase request within a directive instead of a controller. The firebase data retrieved from my directive, is an object with methods on it. Where the data retrieved from my controller is pure json with just the data, that I've inserted.

Directive

angular.module('routerangular')
.directive('raEditor',[ "$firebaseArray", "$firebaseAuth", function( $firebaseArray, $firebaseAuth){
return {
  restrict: 'E',
  replace: true,
  controller: ["$scope", function ($scope) {
    var messagesRef = new Firebase("https://***.firebaseio.com/messages");

    messagesRef.onAuth(authDataCallback);

    function authDataCallback(authData) {
      if (authData) {
        $scope.users = $firebaseArray(messagesRef);

      }  
    }
  }]
};
}]);

I'm trying to access the data by typing {{users}} in the html, but it just says undefined. Below is the output from console.log, where I'm outputting the data I receive from firebase.

[] ***** this is the data I need *****0: Object$id: "-JrIUxOGb54jTV1R9zjy"$priority: nulldescription: "awesome chattionado"userName: "mcChat".....**** To try and keep this short, I have deleted some of the methods from the console.log, not data ****.....  $save: () { [native code] }$watch: () { [native code] }length: 1__proto__: Array[0]

Controller:

In the controller, I'm using almost identical code, but there I'm getting a proper json data set from firebase, where I can retrieve the data by typing {{users}} in the html.

angular.module('routerangular')
.controller('DisplayvideoCtrl', function ($scope, $firebaseObject,       $firebaseArray, $firebaseAuth) {


  var messagesRef = new Firebase("https://****.firebaseio.com/messages");

  messagesRef.onAuth(authDataCallback);
    function authDataCallback(authData) {
      if (authData) {
        $scope.users = $firebaseArray(messagesRef);
      } 
    }
});

the controller is just outputting the data stored in json:

[{"description":"awesome chattionado","userName":"mcChat"}]

What am I missing here? Why am I not able to retrieve data from firebase in a directive.

2

There are 2 answers

0
martin On

Thank you all for replies, I partly figured it out, and think I can work it out. The solution was, that the object from the directive comes with two variables: $id and $value, they can be used in a ng-repeat to produce the keys/values from firebase. Thank you all.

1
Saeed D. On

$scope behaves slightly differently in directives, with isolate scopes only inherit properties explicitly declared. Check out #8 on the top 10 mistakes here Scoping $scope's

Since {{users}} returns an object from your directive, try {{users.description}} and {{users.userName}}.