使用ControllerAs语法的Firebase 3路数据绑定

zor*_*rza 5 javascript angularjs firebase angularfire

我想通过firebase和angularfire获得3路数据绑定.你可以看到我在Plunker里得到的东西:http://plnkr.co/edit/RGA4jZK3Y6n4RkPCHK37

app.js:

angular.module('ideaBattle', ["firebase"]);
Run Code Online (Sandbox Code Playgroud)

服务:

angular
    .module('ideaBattle')
    .constant('FBURL', 'https://ideabattle.firebaseio.com/')
    .service('Ref', ['FBURL', Firebase])
    .factory('dataBank', function(Ref, $firebase) {
        return $firebase(Ref).$asArray();
    });
Run Code Online (Sandbox Code Playgroud)

控制器:

angular
    .module('ideaBattle')
    .controller('ideaListCtrl', displayIdeas);

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

    vm.upVote = function(idea){
        vm.ideas[idea.id].votes++;
    };
}
Run Code Online (Sandbox Code Playgroud)

HTML:

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

Plunker版本:http://plnkr.co/edit/RGA4jZK3Y6n4RkPCHK37

它做什么,它从firebase获取数据并正确显示它,但是当我按下按钮来调用upVote函数时,它只在本地更新.我知道为什么它只在本地工作,但我不知道如何使它也在firebase中更新.

我试着$ bindTo,但是从我的理解它需要$范围工作,我试图用"控制器作为虚拟机"模式,而无需进$范围.

谁能告诉我怎么咬那个?

Dav*_*ast 10

TL;博士; - 3路数据绑定不适用于ControllerAs语法.该bindTo方法需要$scope.

您可以将AngularFire与ControllerAs语法一起使用,但不能将它与ControllerAs一起使用$bindTo.

$bindTo有很强的依赖性,$scope没有它就会破坏.

如果您想要使用带有ControllerAs语法的AngularFire的示例,请查看此Plunker演示.

  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;
  });
Run Code Online (Sandbox Code Playgroud)


J. *_*ein 5

John Papa谈到使用var vm = this;语法而不是$scope每个控制器的目的之一是使用$scope有意识的选择.在这种情况下,我们需要包括$ scope.

我把David East的傻瓜拿回答案,并稍微摆弄了一下.它并不完美,因为它取决于控制器的值是'vm'.

http://plnkr.co/edit/vLLaa7QJvfryYRD7cZvO?p=preview

  .controller('MainCtrl', function(Todos, $scope) { /* Add $scope */
    var vm = this;

    vm.todos = Todos.all();

    vm.lonelyTodo = Todos.get('-JeNOtYPv7AZmVAoZ1bu');
    vm.lonelyTodo.$bindTo($scope, 'vm.lonelyTodo'); /* Add three way binding */
  });
Run Code Online (Sandbox Code Playgroud)