2016-09-07 89 views
0

我有一個場景,我需要在ng-repeat內部動態創建下拉列表,並且下拉列表的數據源也是動態的,這意味着基於我需要綁定我的下拉列表的查詢。ng-options的angularJS控制器方法

因此,我致力於通過傳遞基於查詢的查詢來調用控制器方法,其中我有一個http get,我的服務將返回帶有鍵值對的通用數據。當我調用控制器方法,我結束了王氏infinte循環

錯誤:$ rootScope:infdig 無限$消化循環

我的HTML

<table style="width: 100%"> 
        <tr> 
         <td colspan="2"><strong>Enter Parameters</strong></td> 
        </tr> 

        <tr ng-repeat="x in reportDataParameter.UserParameterList"> 

         <td>{{x.UserParamDefinition.DisplayLabel}}</td> 
         <td> 
          <select ng-model="x.Model" ng-options="item.ValueField as item.TextField for item in executeQuery(x.UserParamDefinition.Query)" class="form-control"> 
           <option value="">Please Select</option> 
          </select> 
         </td> 
        </tr> 
       </table> 

控制器

$scope.reportDataParameter = {};  

    $scope.reportDataParameter = { 
     "UserParameterList": [ 
      { 
       "Key": "StateID", 
       "Value": "?ddl,State,State", 
       "UserParamDefinition": { 
        "DataType": "ddl", 
        "DisplayLabel": "State", 
        "Model": null, 
        "Query": "SELECT Id AS ValueField, BankName AS TextField FROM BankDetail" 
       } 
      }, 
      { 
       "Key": "FacilityParentID", 
       "Value": "?ddl,FacilityParent,FacilityParent", 
       "UserParamDefinition": { 
        "DataType": "ddl", 
        "DisplayLabel": "FacilityParent", 
        "Model": null, 
        "Query": "SELECT Id AS ValueField, Name AS TextField FROM Organization" 
       } 
      } 
     ], 
     "ReportTitle": "Facility List By Parent", 
     "Description": null, 
     "ReportPage": null 
    }; 

$scope.executeQuery = function (query) { 
       var baseUrl = 'https://localhost:62'; 
     return $http.get(baseUrl + '/api/reports/executequery/' + query).then(function (result) { 
      return result.data; 
     }); 
    } 
+0

我建議你儘可能簡化你的代碼問題:讀者和你的一切都會變得更加清晰...... :-)你也應該閱讀你的介紹性文字(第二句expecially )... – MarcoS

回答

1

首先,請記住,每個摘要循環都會評估您在模板中綁定的函數。 executeQuery(x.UserParamDefinition.Query)被稱爲每個摘要週期爲每個ng-repeat條目。在你的情況下,每個週期有兩個函數調用。

此外,每個呼叫使用$http查詢服務器,以便您在每個週期查詢服務器。

然後,您在承諾解決後,在您的ng-options中使用承諾開始一個新摘要並重新調用您的函數。這就是爲什麼你最終會陷入無限循環。除了承諾不是ng-options的有效輸入的問題。

您的回調的return result.data;只是消失在空氣中,因爲它不受控制器的約束,並且不返回executeQuery(返回承諾)。

解決此問題的最簡單方法是將您的查詢數據綁定到UserParameterList條目中的變量,並查詢服務器是否未設置該變量。你可以使用getter方法。這樣的事情也有可能:

$scope.executeQuery = function(item) { 
    var baseUrl = 'https://localhost:62'; 
    $http.get(baseUrl + '/api/reports/executequery/' + item.UserParamDefinition.Query) 
     .then(function (result) { 
      item.queryResult = result.data; 
     }); 
} 

在模板中,你只需要使用x.queryResult。如果UserParameterList不更改,您可以只運行一次陣列,併爲每個條目執行executeQuery。如果確實發生了變化,您可以使用觀察器來追蹤執行executeQuery的更改。如果UserParameterList確實發生了變化,則需要考慮併發性,因爲「在查詢運行時項目可能會更改」並對其進行處理。

+0

優秀的,完美的解決方案。 – Velkumar