我試圖根據對象創建動態表單。 例如:我想生成選擇框將包含選擇,如果給定的,否則工廠將使用AJAX獲取它們,這樣的事情:
標記:
<select ng-repeat="select in selects"
ng-init="options = refactor.options(select)"
ng-options="option in options">
</select>
控制器:
myApp.controller('MyCtrl', function($scope, refactor) {
$scope.refactor = refactor;
$scope.selects = [
{ text: "Country", value="chosen.country", options=["France", "England"] },
{ text: "Gender", value="chosen.gender", options="/gender" }
]
});
工廠:
myApp.factory('refactor', function($scope, $http) {
return {
options: function(select) {
if(typeof(select.options) === 'object') { return select.options };
// otherwise assume select.options is
// a path to fetch options by ajax:
$http.get(select.options).success(function(data) {
select.options = data; // data == ['male', 'female']
});
return []; // placeholder until promise is fulfilled
}
}
})
數據($ scope.selects)克ets按預期更新,但DOM不是,這可能意味着refactor.options()不會再次被調用以響應更改。我嘗試通過將範圍對象傳遞給工廠並調用$ apply來強制更新,但它不起作用。
我錯過了什麼?
試試這個,如果它的工作原理'NG選項= 「select.options中的選項」 – Abdul23
在第一次迭代中,opt離子變量是一個字符串(一條路徑,'/ gender'),它不可迭代,並可能引發異常。 – Kludge
@ Abdul23,你的總體方向畢竟是真的:我在初始化ng-init時使用的變量在更新select.options後沒有任何效果,所以迭代select.options最終解決了這個問題。我建議你發佈這個答案。謝謝。 – Kludge