0

in angularjs modal i am trying to display all classes that have level 4 but i got only one. please how should i alter my could in order to get all the class

$scope.openClass = function (classes) {
    $log.info("classes",classes);
    var modalInstance = $modal.open({
        templateUrl: 'classes.html',
        controller: 'ModalClassInstanceCtrl',
        resolve: {
            info: function () {
                var info = {};
                for (var i=0;i<classes.length;i++){                     
                    if (classes[i].level==4){                           
                        info['name']= classes[i].name;
                        $log.info("classinfo",info);                            
                    }
                }                   
                $log.info(info);
                return info;
            }
    }
});

the $log in if condition show me the write classes they are two in my case but the $log after the for loop show me only one

4
  • 2
    First of all, you should add var in your for loop. Without it, it assumes that iis a global variable. And if using anyway in the script anothervariable named i, you'll have some unexpected results. Commented Jul 6, 2016 at 11:12
  • And it constantly overwrites info['name'] in this code, so you'll only get 1 result. Commented Jul 6, 2016 at 11:15
  • i have added var to my for but how can i prevent it from overwrites , i tried to use break; but it just break after the object and never continue Commented Jul 6, 2016 at 11:22
  • Ofcourse it will stop when you call it to stop. Probably do something like info[]['name'] or info['name'].push(classes[i].name Commented Jul 6, 2016 at 11:23

2 Answers 2

1

You could use the filter method, as the following:

var filteredArray = classes.filter(function(value) {
   return value.level == 4;
));

After it, if you want to pluck only the name of those items you can do the following:

var names = filteredArray.map(function(obj) {
  return obj.name;
}

If you are going to do this often, you could write a function that abstracts away the map, this way:

function pluck(array, key) {
  return array.map(function(item) {
    return item[key]; 
  }); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks developer033 the filteredArray is what i want thanks a lot
0

I think, you overwrite you param "name"

info['name']= classes[i].name;

If you want collection, you should

var info = [];
info.push(classes[i].name)

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.