繁体   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