2016-09-08 3 views
2

ループでは最後のJSONデータのみが表示されますが、解決できません。誰かが私を助けて間違いを教えてくれることを願っています。JavascriptとAngularjsを使用するループ

<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> 

答えて

1

使用angular.forEachループ: -

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

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

あなたは常にループでcurrent item$rootScope.customMarkers =を代入している。このlink

2

を通過する必要があります。 last iterationでは、最後のアイテムデータを取得します。したがって、最初に配列$rootScope.customMarkers = []を作成し、ループ内に新しいオブジェクトを挿入します。

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

これで問題は解決します。

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" 
 
     }); 
 
    } 
 
    });

0

あなたはこのように、各反復であなたの配列を作成するからである。

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



    ];}; 

代わりに、あなたがループする前に配列を作成する必要があるとpushオブジェクトに各繰り返しは、次のようになります。

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