2014-11-26 2 views
0

개체에 레코드를 배열로 추가하는 AngularJS App을 구축하고 있습니다.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

나는 귀하의 문제에서 Lodash가 전혀 문제가되지 않는다고 생각합니다. '$ scope.statistics'가 다시로드 할 때 올바른 값으로 설정되면, Angular를 어떻게 사용하고 있는지가 문제입니다. – Louis

답변

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 
관련 문제