1

I have an Angular app where I am looping through a collection. I am using a classic for loop, but for like to use something more up to date. underscore.js is already included in the project, and I took a look at using _.each

This is my current (working) js code:

Batches.create($scope.newPanel).then(function(panel) {
        console.log('panel created: ' + panel.id);
        for(i = 0; i < $scope.selector.tabledata.length; i++){
            createPanelDetails(panel.id, $scope.selector.tabledata[i]);
        }

I would like to use the _.each, but how do I pass in the panel.id variable as I do with the for loop?

_.each($scope.selector.tabledata, createPanelDetails(panel.id ??, iterator???);

Or should I be using some other method from underscore to achieve this?

4 Answers 4

2

Use an inline function:

_.each($scope.selector.tabledata, function(data) {
    createPanelDetails(panel.id, data);
});
Sign up to request clarification or add additional context in comments.

Comments

1

You could also do this using bind to create a partial function

Underscore:

_.each($scope.selector.tabledata, _.bind(createPanelDetails, undefined, panel.id));

Angular:

angular.forEach($scope.selector.tabledata, angular.bind(undefined, createPanelDetails, panel.id));

2 Comments

What is the meaning of "undefined" in these functions?
@ardochhigh sets this in the bound function to undefined, good thing to point out because if that function is in the scope of an object and the function uses this to refer to that object then the object should be passed instead of undefined
1

via underscore

_.each($scope.selector.tabledata, function(elem) {
  createPanelDetails(panel.id, elem);
});

via angular

angular.forEach($scope.selector.tabledata, function(elem, i){
  createPanelDetails(panel.id, elem);
});

I recommend to follow refrigerator's advice to use angular for consistency.

Comments

1

This is a perfect use case for _.each and _.partial.

_.each($scope.selector.tabledata, _.partial(createPanelDetails, panel.id));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.