ng-repeat 多次,当我调用 try call this

ng-repeats mutliple times when i call try call this

我在我的 laravel 视图上调用 ng-repeat ng-repeat 从控制器中调用一个函数,该函数从数据库中获取数据并进行一些计算,然后重新计算数组,但它一直在返回我的数据不知道为什么任何人都可以帮助我解决为什么 http 请求执行多次?

代码如下 Laravel 查看

<div ng-controller="HotelsListController as hotelLstCntrl">
    <section class="section section-sec top-hotels hotels-sec">
        <div class="container">
            <div class="section-title">
                   <h2>Hotels</h2>
           </div>
           <div class="section-body">
             <div class="owl-carousel owl-theme owl-custom-arrow" id="top-hotels">
                 <div class="item" ng-repeat="hotel_item in hotelLstCntrl.getTopHotels() ">
                     **This exuecute multiple times**
                 </div>
             </div>
          </div>             
        </div>
    </section>
</div> 

angular js控制器

(function(){
  angular
      .module('app')
      .controller('HotelsListController',hotelsListController);

      hotelsListController.$inject = ['$http','dataService','commonMethods'];

      function hotelsListController($http,dataService,commonMethods){

         var vm =  this;
         vm.getHotelsRequests = getHotelData;
         vm.getTopHotels = getTopHotels;

         function getTopHotels(){
             var hotelsLimit =  10;
             var top_hotels = [];    
             //calling the dataService method to get the hotels 
             dataService.getHotels().then((response)=>{
                 top_hotels = response.data.data;
             });
             console.log(top_hotels);
             return top_hotels;              
         }
     }
})();

从api

获取请求的数据服务
(function(){  
    angular
       .module('app')
       .factory('dataService',DataFactory);

       DataFactory.$inject = ['$http']

       function DataFactory($http){
          var service = {};

          service.saveHotels = function(){
            return $http.get('/hotels/saveHotelsData');
          };

          service.getHotels = function(){
            return $http.get('/hotels/getHotelsData'); 
          }
          return service;

       }

})();

可能是当函数 getTopHotels 第一次被调用时 ng-repeat 它 returns [] 因为 promise 还没有解决了。一旦承诺得到解决,top_hotels 将其值从 [] 更改为 response.data.data 中的值。由于 ng-repeat 迭代的值发生了变化,它会重新计算表达式,然后再次调用该函数。

因此,与其直接从 ng-repeat 调用函数,不如使用变量并在控制器初始化时对其进行初始化。像这样:

html

<div class="item" ng-repeat="hotel_item in hotelLstCntrl.top_hotels">
  <!-- --!>
</div>

控制器

// ...
vm.top_hotels = []; // I used the same name you used for this var,
                    // but try to follow a standard for variable names

init(); // I used a new function for initialization for good practice
        // but feel free to call `getTopHotels` directly here,
        // no need to create a new function

function init() {
  getTopHotels();
}

function getTopHotels(){
  // ...
  dataService.getHotels().then((response)=>{
    vm.top_hotels = response.data.data;
  });
  // ...
}