Angularfire $ firebaseArray扩展动态count \ sum

时间:2017-09-27 10:01:06

标签: javascript angularjs arrays firebase angularfire

如果已定义,我试图实现某个节点的动态计数:

这有效,但不是动态的,你必须调用sum()。

app.factory("ArrayWithSum", function($firebaseArray) {
  return $firebaseArray.$extend({
    sum: function() {
       var total = 0;
       var todayDate = new Date();
       var start = todayDate.setHours(0,0,0,0);
       var end = todayDate.setHours(23,59,59,999);

        // the array data is located in this.$list
        angular.forEach(this.$list, function(rec) {
            if (angular.isDefined(rec.qa)){
                if (angular.isDefined(rec.qa.completed)) {
                    if (rec.qa.completed >= start && rec.qa.completed <= end){
                        total++;
                    }
                }
            }

        });
        return total;
    }
  });
});

我尝试了$$更新但无法在数组中访问this_counter:

  app.factory("counter", function($firebaseArray) {
      return $firebaseArray.$extend({
        sum: function() {
            return this._counter;
        },
        $$updated: function(){

           var changed = $firebaseArray.prototype.$$updated.apply(this, arguments);

           var todayDate = new Date();
           var start = todayDate.setHours(0,0,0,0);
           var end = todayDate.setHours(23,59,59,999);

           if( !this._counter ) { 
               this._counter = 0; 
           }

            // the array data is located in this.$list
            angular.forEach(this.$list, function(rec) {
                if (angular.isDefined(rec.qa)){
                    if (angular.isDefined(rec.qa.completed)) {
                        if (rec.qa.completed >= start && rec.qa.completed <= end){
                            this._counter++;
                        }
                    }
                }

            });
          return changed;
        }
      });
    });

有谁知道如何制作一个我可以更新和访问的动态变量?

由于

1 个答案:

答案 0 :(得分:1)

使用$ firebaseObject。显然,您可以将属性_counter添加到对象而不是数组。任何方式都有效,并且是获得动态计数的好方法。

app.factory("counter", function($firebaseObject) {
  return $firebaseObject.$extend({
    $$updated: function(){

       var changed = $firebaseObject.prototype.$$updated.apply(this, arguments);

       if( !this._counter ) { this._counter = 0; }

       var total = 0;
       var todayDate = new Date();
       var start = todayDate.setHours(0,0,0,0);
       var end = todayDate.setHours(23,59,59,999);

        // the array data is located in this.$list
        angular.forEach(this, function(rec) {
            if (angular.isDefined(rec.qa)){
                if (angular.isDefined(rec.qa.completed)) {
                    if (rec.qa.completed >= start && rec.qa.completed <= end){
                        total++;
                    }
                }
            }

        });

      this._counter = total;
      return changed;
    }
  });
});


vm.panels = new counter(panelsRef);

{{vm.panels._counter}}

手表在IE11上长时间没有射击后出现问题。所以我想我尝试这种方法。