Transform business object into view model in angular-meteor

328 views Asked by At

Background

I have an angular-meteor app and a collection of business objects in mongodb, e.g.:

{ startDate: new Date(2015, 1, 1), duration: 65, value: 36 }

I want to render this data in different views. One of the views is a graph, another is a list of entries. The list of entries is easy. Just bind the collection to the model:

vm.entries = $scope.meteorCollection(MyData, false);

In the view I would do:

<div ng-repeat="entry in vm.entries">{{entry.startDate}} - ...</div>

But now for the graph. I want to transform each element into a { x, y } object and give the view that, e.g.:

vm.graphPoints = transformData(getDataHere());

The problem is that the data is not fetched here, in angular-meteor is looks like it is fetched when calling the entry in vm.entries in the view. The kicker is that the transformData method, needs to loop through the data and for each item index into other items to calculate the resulting x, y. Hence I cannot use a simple forEach loop (without having access to the other items in some way).

Question

So how can i fetch the data in the controller - transform it - and still have one-way binding (observing) on new data added to the database?

Thanks

Update

The following code works, but I think there could be performance problems with fetching the whole collection each time there is a change.

$scope.$meteorSubscribe("myData").then(function() {
    $scope.$meteorAutorun(function() {
        var rawData = MyData.find().fetch();
        vm.model.myData = transformData(rawData);
    });
});
2

There are 2 answers

4
oshai On

EDIT:
This is the current solution:

$scope.collectionData = $scope.meteorCollection(MyData, false);
$meteor.autorun($scope, function() {
        vm.graphPoints = transformData($scope.collectionData.fetch());
    });

There is some missing information. do you wan't to have some kind of model object in the client? if that is correct I think you have to do something like this:

$meteor.autorun($scope, function() {
        vm.graphPoints = transformData($scope.meteorCollection(MyData, false));
    });
1
Urigo On

How about using the Collection Helper Meteor package to add the function: https://github.com/dburles/meteor-collection-helpers/ ?