zorza zorza - 4 months ago 7
Javascript Question

Firebase 3-way data binding with ControllerAs syntax

I'm tring to get 3-way data binding with firebase and angularfire. You can see what I've got in Plunker: http://plnkr.co/edit/RGA4jZK3Y6n4RkPCHK37


angular.module('ideaBattle', ["firebase"]);


.constant('FBURL', 'https://ideabattle.firebaseio.com/')
.service('Ref', ['FBURL', Firebase])
.factory('dataBank', function(Ref, $firebase) {
return $firebase(Ref).$asArray();


.controller('ideaListCtrl', displayIdeas);

displayIdeas.$inject = ['dataBank'];
function displayIdeas(dataBank){
var vm = this;
vm.ideas = dataBank;

vm.upVote = function(idea){


<div ng-controller="ideaListCtrl as vm">
<div ng-repeat="idea in vm.ideas | orderBy: '-votes'">
<p>{{idea.desc|limitTo: 190}}</p>
<span class="btn" ng-click="vm.upVote(idea)">Vote! <span class="badge"> {{idea.votes}}</span></span>

Plunker version: http://plnkr.co/edit/RGA4jZK3Y6n4RkPCHK37

What it does, it gets the data from firebase and displays it correctly, but when I push the button to call upVote function it only updates locally. I know why it only works locally, but I don't know how to make it also update in firebase.

I've tried with $bindTo, but from what I understand it requires $scope to work, and I'm trying to use "Controller as vm" pattern without injecting $scope.

Can anybody tell me how to bite that?


tl;dr; — 3-way data-binding does not work with ControllerAs syntax. The bindTo method requires $scope.

You can use AngularFire with ControllerAs syntax, but you can't use it with ControllerAs with $bindTo.

$bindTo has a hard dependency on $scope and it will break without it.

If you want an example of using AngularFire with ControllerAs syntax, check out this Plunker demo.

  angular.module('app', ['firebase'])

  // constant for the Firebase we're using
  .constant('FBURL', 'https://<your-firebase>.firebaseio.com/todos')

  // return the Firebase ref as a service
  .service('Ref', ['FBURL', Firebase])

  // return the Todos from Firebase by returning the
  // array from the factory 
  .factory('Todos', function(Ref, $firebase) {
    return $firebase(Ref).$asArray();

  // inject the Todos and assign them to "this"
  // for the ControllerAs syntax
  .controller('MainCtrl', function(Todos) {
    this.todos = Todos;