簡體   English   中英

如何從中預選選項 <select>在Angular中添加來自其他控制器的選項的標簽?

[英]How to pre-select option from <select> tag in Angular with options from a different controller?

我在這里使用兩個控制器。 其中一個是productComponentsController ,它處理對我們數據庫的調用,該調用將拉回productComponent對象的數組。 另一個AddEditArticleController ,控制“創建新的/編輯現有文章”頁面。

在我的“添加/編輯文章”頁面上,我希望<select>填充有productComponents ,並且,如果我正在編輯現有文章,則希望與該文章的當前productComponent一起預先選擇。

看起來很簡單,我不能使用現有的productComponent來使該字段預先選擇,盡管它確實用它們正確填充了<select> 我試過了ngRepeat和ngOptions,它們都可以用來填充下拉列表,但是都不能從服務器返回的數組中預選擇現有的productComponentID

我的HTML,使用ngOptions:

 <!-- productComponentsController as pvm, AddEditArticleController as vm --> <select id="componentBox" ng-model="vm.selectedComponent" placeholder="Select a Product Component" ng-change="vm.changeProductID()" class="form-control input-md" ng-options="component.name for component in pvm.productComponents track by component.id"></select> 

我的HTML,使用ngRepeat:

 <!-- productComponentsController as pvm, AddEditArticleController as vm --> <select id="componentBox" ng-model="vm.selectedComponent" placeholder="Select a Product Component" ng-change="vm.changeProductID()" class="form-control input-md"> <option value="{{component.id}}" ng-repeat="component in pvm.productComponents" ng-selected="vm.selectOption(component.id)" ng-bind-html="component.name"></option> </select> <!-- vm.selectOption() returns true if the current option's ID equals the productComponentID of the current Article. Therefore this option would be selected. --> 

在我的AddEditArticleController ,在AddEditArticleController ,將vm.selectedComponent設置為等於數據庫返回的Article的productComponentID 盡管vm.selectedComponent確實發生了變化,但這對下拉列表沒有任何作用。

另外,在生成的HTML中,我得到以下選項: <option value="? number:47 ?"></option> (對於productComponentID為= 47的文章)。 顯然,這是由於將模型設置為未知值而導致的,但是我不知道為什么將模型設置為除整數id之外的任何值。

這是因為我的選擇正在訪問多個控制器,還是我在這里遺漏了一些明顯的東西? 非常感謝您的幫助,如果需要更多信息,請告訴我。

我相信你正在尋找ng-init ...

 <!-- productComponentsController as pvm, AddEditArticleController as vm --> <select id="componentBox" class="form-control input-md" placeholder="Select a Product Component" ng-change="vm.changeProductID()" ng-model="vm.selectedComponent" ng-init="vm.selectedComponent=productComponentID" ng-options="component as component.name for component in pvm.productComponents track by component.id"></select> 

事實證明,因為模型必須是字符串,所以每當使用String()對其進行更改(在本例中,在vm.selectOption函數中)時,我都必須將vm.selectedOption轉換為字符串。 這是使用ngRepeat。 ngInit似乎與我的代碼的工作方式無關。

就是這樣,我的代碼正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM