2

Loops only show the last JSON data and I can not resolve it, hope someone can help me and tell me what's wrong am I, thank you.

    <script>
  angular.module('ngMap').run(function($rootScope) {
    $rootScope.mouseover = function() {
      console.log('mouseover', this);
      this.style.backgroundColor = 'grey';
    };
    $rootScope.mouseout = function() {
      this.style.backgroundColor = 'white';
    };
    $rootScope.click = function() {console.log('click')};
    for (var i = 0; i < map_data.length; i++) {
    $rootScope.customMarkers = [
      {address: map_data[i].work_address, "class": "my1"},



    ];};
  });
</script>

3 Answers 3

2

You're always assigning the $rootScope.customMarkers = to the current item in the loop. in the last iteration you would get the last item data. So, first create a array $rootScope.customMarkers = [] and then in the loop push the new object into it.

$rootScope.customMarkers.push({
   address: map_data[i].work_address,
   "class": "my1"
});

This should solve the problem.

  angular.module('ngMap').run(function($rootScope) {
    $rootScope.mouseover = function() {
      console.log('mouseover', this);
      this.style.backgroundColor = 'grey';
    };
    $rootScope.mouseout = function() {
      this.style.backgroundColor = 'white';
    };
    $rootScope.customMarkers = [];
    $rootScope.click = function() {
      console.log('click')
    };
    for (var i = 0; i < map_data.length; i++) {
      $rootScope.customMarkers.push({
        address: map_data[i].work_address,
        "class": "my1"
      });
    }
  });

Sign up to request clarification or add additional context in comments.

Comments

1

Use angular.forEach loop:-

var log = [];
angular.forEach(values, function(value, key) {
  // Write your logic here

   this.push(key + ': ' + value);
}, log);

You should go through this link

Comments

0

It is because you create your array in each iteration, like this:

 $rootScope.customMarkers = [
      {address: map_data[i].work_address, "class": "my1"},



    ];};

Instead, you need to create the array before the loop and push the object in each iteration, like this:

$rootScope.customMarkers = [];
for (var i = 0; i < map_data.length; i++) {
    $rootScope.customMarkers.push({address: map_data[i].work_address, "class": "my1"});
};

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.