I recently started studying a bit of AngularJS (with almost no previous experiences in programming). I would like to create a tool for statistical analysis and to do so I worked on a few "proof-of-concept" examples.
Like this one: http://jsfiddle.net/nitecorp/udcjnoxo/
It works but I have the feeling that the way I am using the functions is highly inefficient:
<tr>
<td>Average Age</td>
<td>{{getAverage()}}</td>
</tr>
<tr>
<td>Younger</td>
<td>{{getStats(getAges())['younger']}}</td>
</tr>
<tr>
<td>Older</td>
<td>{{getStats(getAges())['older']}}</td>
</tr>
Question What is the right approach to store getAges and use the results instead of recalculating every time? Same for getStats: can I just store the values instead of recalculating twice (in the example)?
Note: In this example is not a big deal, but I need to apply that code to a more complex scenario, with more complex stats (standard deviation, variance etc) and using more than 1M values...
Thanks
Use a $watch to listen for updates to your data structure, then update your variables accordingly.
I've created a fork of your fiddle to illustrate this, with the code below demonstrating the important bits:
$scope.$watch(
function(scope) {
return $scope.dogs.length;
},
function(oldVal, newVal) {
console.log('dogs changed');
$scope.updateStats($scope.getAges());
$scope.updateAverage();
});