问题
I have an AngularJS service that returns a firebase ref.
.factory('sessionManager', ['$firebase','$scope', function($firebase){
var ref=new Firebase('https://telechat.firebaseio.com/sessions');
return $firebase(ref);
}])
In the controller, I have added the dependency and called $bind
.
$scope.items=sessionManager;
$scope.items.$bind($scope,'sessions').then(function(unbind){
unbind();
});
But when I print it to the console, the returned data has a collection of functions like $add
, $set
,.. etc in addition to the array of data.
Why is this occurring? Am I doing it the wrong way?
回答1:
If I'm reading the question correctly, you may be under the impression that $bind() is a transformation of the $firebase object into a raw data array or object. In essence, the only difference between a $firebase instance and $bind is that data is local changes are automagically pushed back to Firebase from Angular. Whereas, when you use $firebase without $bind, you need to call $save to push local changes.
Keeping in mind that $firebase is a wrapper on the Firebase API and not a simple data array, you can still treat it like raw data in most cases.
To iterate data in a Firebase object, you can use ngRepeat:
<li ng-repeat="(key, item) in $sessions">{{item|json}}</li>
Or if you want to apply filters that depend on arrays:
<li ng-repeat="(key, item) in $sessions | orderByPriority | filter:searchText">
Or in a controller using $getIndex:
angular.forEach($scope.sessions.$getIndex(), function(key) {
console.log(key, $scope.sessions[key]);
});
The $add/$update/etc methods mentoined are part of the $firebase object's API. The documentation and the tutorial should be great primers for understanding this process.
This is also a part of the API that is continuing to evolve to better match the Angular way of doing things and feedback from users.
来源:https://stackoverflow.com/questions/22267077/firebase-3-way-data-binding-not-working-as-expected