yar1
yar1

Reputation: 1351

Angular: where to calculate values

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:

  1. In the controller and add the calculated value to the $scope - <div>{{lastVisit}}</div>
  2. Using a $scope method - <div>{{getLastVisit()}}</div>
  3. In the view (this definitely doesn’t feel right) - <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

Answers (3)

sethro
sethro

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

kamilkp
kamilkp

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

Sai
Sai

Reputation: 2068

My personal preference on the above approaches:

  1. Yes, the best approach, since you don't have your business logic in your view.
  2. This will have the same effect as the 1st option, but accessing Model from view comes under best practices.
  3. No, since your business logic might change in future.

Upvotes: 0

Related Questions