e_hoog
e_hoog

Reputation: 37

Adding new object properties in ng-repeat for each object

I'm fairly new with AngularJS so please excuse my ignorance and improper terminology.

I have a Controller called activitiesController that returns an array of activity objects. Each activity object has some properties which I can display in the view using ng-repeat="activity in activities".

One of the properties is a big string that I need to hack apart and essentially add to new properties of the activity object (I know this is horrible but it's from a legacy system).

Do I run a function in ng-repeat like ng-repeat="activity in getNewProperties(activities)" where I would loop through each activity and return the array back to ng-repeat.

OR

Do I just make a function in the scope that will return each property that I'm looking for.

Ideally in the view I would just use activity.newDetails.NewValue which makes me beielve i need to run my function on all of the activity objects before they are passed to ng-repeat in the view.

Sorry I know this isn't very details I can try to add more shortly.

Upvotes: 0

Views: 947

Answers (1)

Jaydo
Jaydo

Reputation: 1849

Do I run a function in ng-repeat like ng-repeat="activity in getNewProperties(activities)" where I would loop through each activity and return the array back to ng-repeat.

Let's say you did this and the function looks something like this:

$scope.getNewProperties = function(activities) {
  var modifiedActivities = [];
  for (var i = 0; i < activities.length; i++) {
    var modifiedActivity = activities[i];
    modifiedActivity.foo = "bar";
    modifiedActivities.push(modifiedActivity);
  }
  return modifiedActivities;
};

This function will run in every $digest cycle. Besides from being resource consuming, it also means that if you make changes to modified properties (in this case foo), the next time this function runs, the property will be overwritten by this function.

What you want to do is modify $scope.activities as soon as you get the data. This way it will only occur once unless you refresh the data. e.g.

$http.get("http://somewebsite/api").then(function(response) {
  $scope.activities = response.data;

  for (var i = 0; i < $scope.activities.length; i++) {
    // modify properties
  }
});

Upvotes: 1

Related Questions