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

Javascript 使用LoDash和AngularJS进行实时同步更新,javascript,angularjs,lodash,Javascript,Angularjs,Lodash,我正在构建一个AngularJS应用程序,其中我以对象的形式将记录添加到数组中 我已经设法使用LoDash从这些数据中获取统计数据(您可以看到相关的问题) 但是作为SPA,我需要在向数组中添加记录时更新统计数据($scope.recordlist),到目前为止,它们只在我重新加载页面时更新 以下是相关代码: var dataByMonth = _.groupBy($scope.recordlist, function(record) { return moment(record.dat

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

我已经设法使用LoDash从这些数据中获取统计数据(您可以看到相关的问题) 但是作为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;

我错过了什么?

这只是做了一些假设,但应该做你想做的。基本上,将代码包装到函数中,然后
$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

我怀疑洛达斯是你问题中的一个因素。如果重新加载时将
$scope.statistics
设置为正确的值,则可能的问题是如何使用Angular。