Reputation: 1204
When you have an array of objects, how do you go about binding the changes of an object to firebase?
data looks like this:
[{ title: "Do Something", Due: "1425121200000", assignedTo: "Bill", description: "Do something", $id: wqejkkjebiewdf},
{ title: "Do Something else", Due: "1425121200000", assignedTo: "Jim", description: "Do something else", $id: owenuwefwfliu}]
js:
var todos = this;
todos.tasks = [];
var todoRef = new Firebase(FB + "/tasks/" + CurrentFarm);
var todoArray = $firebase(todoRef).$asArray();
todoArray.$loaded(todos.tasks = todoArray);
html to show todos:
<div ng-repeat="task in todo.tasks | orderBy:'when'| filter: {done: true}">
<input type="checkbox" ng-model="task.done" ng-change="todo.taskDone(task)">
<span ng-repeat="users in task.users">{{getName(users)}} </span>
<span> {{task.title}} </span>
<span> {{task.when | date:"EEEE, d MMMM, y"}} </span>
<input ng-click="editTask()" type="button" value="Edit">
</div>
html for editing a todo. Note that I removed certain inputs from this code like date pickers etc to make it more readable.
<div ng-show="editTaskMenu">
<form novalidate>
<input ng-model="task.title" type="text" value="{{task.title}}">
<textarea ng-model="task.description" value="{{task.description}}"></textarea>
<input type="submit" value="Done" ng-click="finishedEditing()">
</form>
</div>
The changes bind to the array in angular but do not get updated in firebase. From what I can tell there is no way to do three way binding with an array, so what is the work around here?
Upvotes: 0
Views: 3720
Reputation: 3526
AngularFire accomplishes three-way binding, which is what you're looking for.
Take a look at the quick-start guide.
From the quick-start guide:
To sync data as an object:
var app = angular.module("sampleApp", ["firebase"]);
app.controller("SampleCtrl", function($scope, $firebaseObject) {
var ref = new Firebase("https://<your-firebase>.firebaseio.com/data");
// synchronize the object with a three-way data binding
var syncObject = $firebaseObject(ref);
syncObject.$bindTo($scope, "data");
});
Source: https://www.firebase.com/docs/web/libraries/angular/quickstart.html#section-objects
When you do that, syncObject
will be bound to $scope.data
, and any changes to $scope.data
will update syncObject
, and hence the data at the firebase location.
But what you want is $firebaseArray
like so:
var app = angular.module("sampleApp", ["firebase"]);
app.controller("SampleCtrl", function($scope, $firebaseArray) {
var ref = new Firebase("https://<your-firebase>.firebaseio.com/messages");
// create a synchronized array for use in our HTML code
$scope.messages = $firebaseArray(ref);
});
Source: https://www.firebase.com/docs/web/libraries/angular/quickstart.html#section-arrays
Here is the full AngularFire API documentation
Upvotes: 1