javascript - 使用 ControllerAs 语法的 Firebase 3 向数据绑定(bind)

标签 javascript angularjs firebase angularfire

我正在尝试使用 firebase 和 angularfire 进行三向数据绑定(bind)。你可以看到我在 Plunker 中得到了什么:http://plnkr.co/edit/RGA4jZK3Y6n4RkPCHK37

app.js:

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

服务:

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

Controller :

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++;
    };
}

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>

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

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

我尝试过使用 $bindTo,但据我了解它需要 $scope 才能工作,并且我正在尝试使用“Controller as vm”模式而不注入(inject) $scope。

谁能告诉我怎么咬那个?

最佳答案

tl;博士; — 3 向数据绑定(bind)不适用于 ControllerAs 语法。 bindTo 方法需要 $scope

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

$bindTo$scope 有硬依赖,没有它它会崩溃。

如果您想要一个使用 AngularFire 和 ControllerAs 语法的示例,请查看 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;
  });

关于javascript - 使用 ControllerAs 语法的 Firebase 3 向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27367289/

相关文章:

javascript - 隐藏/显示不同的链接

node.js - 为什么 process.env.FIRESTORE_EMULATOR_HOST 在测试环境中是未定义的?即使我已经运行了模拟器

firebase - Flutter Cloud Firestore 将 serverTimestamp 转换为字符串

ios - 关于动态链接的行为

javascript - 我可以用 HTML5 + 其他网络技术实现这一点吗?

javascript - 如何在不重新加载页面的情况下更改 BrowserWindow 哈希 url

html - 当变量变为真时,angular js 添加 css

c# - WebApi CORs - 请求错误时存在 Access-Control-Allow-Origin header

javascript - Angular 多选图表

javascript - Django Rest框架和React前端: How to prevent unauthorized users from viewing private images if they get a hold of the image URL?