【问题标题】:Loops using Javascript and Angularjs使用 Javascript 和 Angularjs 的循环
【发布时间】:2016-09-08 09:46:32
【问题描述】:

Loops 只显示最后的 JSON 数据,我无法解决,希望有人能帮助我,告诉我哪里出了问题,谢谢。

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

【问题讨论】:

    标签: javascript angularjs google-maps loops


    【解决方案1】:

    您总是在循环中将$rootScope.customMarkers = 分配给current item。在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"
          });
        }
      });

    【讨论】:

      【解决方案2】:

      使用angular.forEach循环:-

      var log = [];
      angular.forEach(values, function(value, key) {
        // Write your logic here
      
         this.push(key + ': ' + value);
      }, log);
      

      你应该通过这个link

      【讨论】:

        【解决方案3】:

        这是因为您在每次迭代中都创建了数组,如下所示:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-15
          • 1970-01-01
          • 1970-01-01
          • 2023-04-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-23
          相关资源
          最近更新 更多