使用LoDash和AngularJS进行实时同步更新

时间:2014-11-26 18:48:09

标签: javascript angularjs lodash

我正在构建一个AngularJS应用程序,我将对象形式的记录添加到数组中。

我已设法使用LoDash从这些数据中获取统计信息(您可以看到相关问题here) 但作为SPA,我需要在将数据添加到数组($scope.recordlist)时更新统计信息,到目前为止,只有在我重新加载页面时才会这样做。

以下是相关代码:

var dataByMonth = _.groupBy($scope.recordlist, function(record) { 
    return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); 
});

dataByMonth = _.mapValues(dataByMonth, function(month) {
    var obj = {};
    obj.Cars = _.groupBy(month, 'car');
    obj.Drivers = _.groupBy(month, 'driver');

    _.each(obj, function(groupsValue, groupKey) {
        obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
            return _.reduce(groupValue, function(sum, trip) {
                sum['trips']++;
                sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                sum['total'] = moment.utc(sum.duration). format('HH:mm:ss')
                //addDuration(sum.duration, car.duration); 
                return sum;
            }, {trips: 0, duration: 0, total:0})
        });
    })

    return obj;
});

$scope.statistics = dataByMonth;

我错过了什么?

1 个答案:

答案 0 :(得分:1)

这是做一些假设,但应该做你想要的。基本上将代码包装在一个函数中,然后$watch $scope.recordlist包含调用函数的更改。

$scope.refreshStats = function() {
    var dataByMonth = _.groupBy($scope.recordlist, function(record) { 
        return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); 
    });

    dataByMonth = _.mapValues(dataByMonth, function(month) {
        var obj = {};
        obj.Cars = _.groupBy(month, 'car');
        obj.Drivers = _.groupBy(month, 'driver');

        _.each(obj, function(groupsValue, groupKey) {
        obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
            return _.reduce(groupValue, function(sum, trip) {
                sum['trips']++;
                sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                sum['total'] = moment.utc(sum.duration). format('HH:mm:ss')
                //addDuration(sum.duration, car.duration); 
                return sum;
            }, {trips: 0, duration: 0, total:0})
        });
        })

        return obj;
    });

    $scope.statistics = dataByMonth;
};

$scope.refreshStats(); // for init onload

$scope.$watch('recordlist', $scope.refreshStats, true); // for handling updates w/o reload