Reputation: 1351
Given an array of “visits” [{ date:DATE, summary:TEXT }, { date:DATE, summary:TEXT }, …]
, if I need to show the last visit, where would I do the calculation:
<div>{{lastVisit}}</div>
<div>{{getLastVisit()}}</div>
<div>{{visits[visits.length-1]}}</div>
I am avoiding for now the question whether the model should be manipulated inside the controller or in its own service.
Upvotes: 0
Views: 272
Reputation: 2127
Option 1: Doing calculations in the controller and storing the value to $scope
. When that value is updated, angular will automatically update your view. This is likely what you want.
To clarify: In your controller, when the visits
array is updated ( element added, deleted, etc... ), calculate the last visit value and store it to $scope.lastVisit
.
var function newVisit( visit ){
visits.append( visit );
$scope.lastVisit = visit; // this will update your view
}
Why I don't think option 2 is right: Angular will be binding the function and not the value itself. Binding to the value itself is likely what you mean.
You are correct about 3, keep logic out of the view if possible.
Upvotes: 0
Reputation: 9800
With option 1, you'd have to add a watch to update the lastVisit
in model any time the visits
array changes. Option 2 is better but requires writing an additional one-liner function in your model.
The third option is legit and require zero javascript so if you only need to simply show the last element of the array this is the way to go. It's also the most efficient as it doesn't require any additional objects in memory, and doesn't call any other function (than angular parse internally)
If you don't want the logic in your view, Option 2 is your best choice. But I would create a more generic method that returns the last element of the array like that:
<div>{{getLastItem(visits)}}</div>
$scope.getLastItem = function(arr){
return arr[arr.length - 1];
};
See fiddle: http://jsfiddle.net/hZM23/1/
Upvotes: 1
Reputation: 2068
My personal preference on the above approaches:
Upvotes: 0