I've been diving into AngularJS and it's been quite fascinating, although I do run into some architectural challenges at times. Let me illustrate with an example.
Imagine we have an application that enables users to create bills. Each bill consists of various lines representing different goods or services, each with properties like title, quantity, cost, and total amount. In JSON format, it might look something like this:
"goods": [
{
"title": "Apple",
"quantity": 3,
"cost": 5.00,
"sum": 15.00 // 5.00 × 3
},
{...}
]
Additionally, a bill has a total amount calculated by adding up all the item sums. For instance, if we have 3 apples costing $15.00 and 5 bananas costing $10.00, the total bill amount would be $25.00.
The debate arises on the most effective way to calculate amounts within each scope. One method involves having only one scope (for the bill) with predefined methods for sum calculation in every step. Here's a basic pseudocode representation:
$scope.getTotalInItem = function(item) {
return item.quantity * item.cost
}
$scope.getTotal = function() {
amount = 0
for item in $scope.items
amount += $scope.getTotalInItem(item)
return amount
}
While this approach simplifies data retrieval from the server without much preparation, it tends to mix all the logic in a single place, which may not be ideal.
Alternatively, another tactic involves creating a separate class for each calculation level, like so:
function Good(title, quantity, cost){
this.total = function(){
return this.quantity * this.cost
}
}
function Bill(goods){
this.goods = goods
this.total = function(){
amount = 0
for good in this.goods
amount += good.total()
return amount
}
}
This approach, with its delineation of logic levels, seems more organized. However, integrating it effectively with Angular remains a challenge. This method doesn't lend itself easily to fetching JSON data directly from the server and modifying it.
You can find a demonstration of these two approaches here: http://plnkr.co/edit/7t56sIUY83Rnowe8Zb3z?p=preview
In my opinion, it seems necessary to prepare the model after each data fetch and before any data push. This requires convenient helper functions like toJSON() and fromJSON(). What would be considered best practice for implementing such tasks with Angular?