【问题标题】:How to use angular forEach with firebase如何在 Firebase 中使用 Angular forEach
【发布时间】:2014-07-12 05:22:38
【问题描述】:

我是角度新手。我正在尝试将 Angular foreach 与 Firebase 一起使用,但它没有用。有关如何执行此操作的任何指示?

var app = angular.module('MyApp',["firebase"]);
    app.controller('ItemCtrl', function($scope, $firebase){
      var ref = new Firebase("https://url.firebaseio.com");
        $scope.menu = $firebase(ref);

        $scope.total = function(){
            var total = 0;

            angular.forEach($scope.menu, function(item) {

              total += item.price * item.quantity;

          })

          return total;

          };

    });

html

<div class=" sliding" >
  <a href="#"class="button open" >
     Total: {{total() | currency}}
  </a>
</div>

json

[
         {"name": "Ham, Egg & Cheese CROISSAN'WICH ",
          "quantity": 0,
          "price": 20, 
          "description": "description", 
          "comment": "comment",
          "imgURL": "http://url"    },
...]

【问题讨论】:

  • 您确定正确包含 angular fire 和 Firebase 吗?
  • 是的,很确定。我可以从 firebase 获取数据,$scope.menu 工作正常。
  • 错误:[$interpolate:interr] 无法插值:总计:{{total() |货币}} ReferenceError: total 未定义
  • 您的视图如何?

标签: javascript angularjs firebase angularfire


【解决方案1】:

与其尝试枚举 AngularFire,我们可以监听 Firebase 中构成我们总数的任何更改。因此,每次更改项目时,我们都可以自动更新总值。

$scope.menu 上,为change 事件附加一个$on 侦听器。然后我们可以提供一个回调函数来计算$scope 上的属性的总数。然后在我们看来,我们不必调用函数,我们只需绑定$scope 上的总属性即可。

Plunker Demo

  var app = angular.module('app', ['firebase']);

  app.constant('FBURL', 'https://<your-firebase>.firebaseio.com/items');
  app.service('Ref', ['FBURL', Firebase]);

  app.controller('ItemCtrl', function($scope, $firebase, Ref) {

    $scope.menu = $firebase(Ref);
    $scope.total = 0;

    // Listen for any changes in firebase
    //
    // The $on listener will take a event type, "change" 
    // and a callback function that will fire off for each
    // item that has been changed. On the initial page load
    // it will return each item at the location one at a time
    //
    // Remember that AngularFire automatically updates any changes 
    // for us, so we just need to get the key back from the callback
    $scope.menu.$on('change', function(key) {
      // the key is the object's key in Firebase
      var item = $scope.menu[key];
      $scope.total += item.price * item.quantity;
    });

  });

观点

<div class="sliding">
  <a href="#" class="button open">
    Total: {{ total }}
  </a>
</div>

【讨论】:

  • 呃......如果我想修改firebase中的数据,我应该怎么做,比如增加数量。
  • 这也很简单!再问一个问题,我在那里回答会比在 cmets 中容易得多。
猜你喜欢
  • 2020-08-27
  • 1970-01-01
  • 2021-02-16
  • 2021-08-13
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2019-07-10
  • 2017-01-21
相关资源
最近更新 更多