2015-04-25 39 views
1

我有以下的 「主模板」:無限循環使用NG-包括

<html ng-app="myApp"><head/> 
<body ng-controller="HomeController"> 
<div class="container" id="mainContent" ng-include="'dashboard/'+menu()+'.html?v='+getRandom()"></div> 
</body> 

歸屬內置控制器我按 「菜單」 - 參數的內容包括:

myApp.controller('HomeController',function($scope,$location) { 

    $scope.menu=function() { 
     var submenu=$location.search().menu; 
     if (submenu===undefined) { 
      submenu="home" 
     } 
     return submenu; 
    }, 
    $scope.getRandom=function() { 
     return Math.floor((Math.random()*6)+1); 
    }, 
    $scope.$on('$includeContentLoaded', function(event) { 
     $(".bsSwitch").bootstrapSwitch(); 
    }); 
}); 

(隨機部分僅用於在我的開發環境中停止緩存)

包含的模板如下所示:

<div class="easyBox" ng-controller="CompanyController" ng-init="init()"> 
<span>nothing to see at all</span> 
</div> 

並具有以下控制器:

myApp.controller('CompanyController',function($scope,$http,$location) { 
    $scope.init=function() { 
     $http.get('company/get/mine'). 
      success(function(data,status,headers,config) { 
       aboutMe=data; 
       console.log("nice"); 
      }). 
      error(function(data,status,headers,config){ 
       console.log("there was an error"); 
       // redirectToLogin(); 

      }); 
    }, 
    $scope.aboutMe 
}); 

現在的問題是,在init() - 從companyController函數被調用的無限循環。什麼可能導致這個問題,如何解決?

回答

2

其中之一,你永遠不應該使用一個監視的表達式,在每個摘要循環中改變它的值。 "... + getRandom()"將永遠不會穩定 - 並且會導致「無限循環」,在10次摘要迭代之後Angular會停止。

如果你需要避免與隨機URL緩存,然後計算該URL一旦控制器功能運行時,並將其分配給一個範圍變量:

$scope.menuUrl = "dashboard/" + menu() + ".html?v=" + getRandom(); 

(也,不必申報menu爲您節省和getRandom的範圍 - 只要保持它作爲控制器內的私有函數)

,並使用與ng-include

<div ng-include="menuUrl"></div> 

另一件事,雖然與您的問題沒有關係,但使用ng-init--根本不需要。當使用ng-controller指令時,控制器功能將運行一次(因此它是init函數):

myApp.controller('CompanyController', function($scope, $http, $location) { 
    $http.get('company/get/mine') 
     .success(function(data,status,headers,config) { 
      $scope.aboutMe = data; // this was also a bug 
            // assigning data to a global var aboutMe 
      console.log("nice"); 
     }) 
     .error(function(data,status,headers,config){ 
      console.log("there was an error"); 
      // redirectToLogin(); 
    }); 
}); 
+0

謝謝。我更新了我的問題(遵循你的建議)。仍然無止境的循環(並且遠遠超過10次(無限))似乎是造成所有麻煩的$ get() –

+0

那麼,你不應該編輯問題本身的原始內容 - 這會使得答案變得毫無意義尊重這個問題)給未來的參觀者。保持原始問題不變,如有需要,請在底部添加說明。 –

+0

@OleAlbers,它適用於我:http://plnkr.co/edit/G3T0PJWb7lMPt44xSRBD?p=preview –