动态选择列表默认选定项-Angular JS [英] Dynamic Select List Default Selected Item - Angular JS

查看:93
本文介绍了动态选择列表默认选定项-Angular JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面列出的代码,可以正常工作,但是,当我尝试将ng-model和相关的ng-change添加到select中时,将添加一个空选项.我知道为什么,这是因为在初始化时ng-model的selectedOption为空.

I have the code listed below which works fine, however when i attempt to add ng-model and related ng-change to the select, an empty option is added. I understanding why, it is because on init the selectedOption for ng-model is empty.

我想做的是设置一个默认值,这样当我可以使用ng-change将用户选择的IsSelected值设置为true时.我只是不确定该怎么做,当我使用静态生成的选择列表时,这样做没有问题,但是由于某种原因,我无法为这个动态生成的列表弄清楚.

What I want to do is set a default value so when I can use ng-change to set options IsSelected value to true when user selects it. I'm just not sure how to go about this, I have no issues doing this when I'm working with a static generated select list, but for some reason I can't figure it out for this dynamic generated list.

感谢任何输入!

    <div ng-repeat="optionType in productDetailModel.OptionTypes">
         <select name="{{optionType.OptionTypeName}}">
            <option ng-repeat="option in optionType.Options"
             value="{{option.OptionValue}}">{{option.OptionValue}}
            </option>
         </select>
     </div>

我嘲笑的是这里的plunkr,它提供了我所想的基本概念: http://plnkr.co/edit/xBDfc0XzDwsF0mBiFZOv?p=preview

Here's plunkr I mocked to give a basic idea of what I have in mind: http://plnkr.co/edit/xBDfc0XzDwsF0mBiFZOv?p=preview

推荐答案

初始选项为空,因为最初未定义模型. 就像tymeJV所说的那样,在.js内部初始化作用域将定义一个默认值,该值将显示为最初选择的状态.

The initial option is blank because the model is initially undefined. As tymeJV said, initializing your scope inside of your .js will define a default value that will be shown as selected initially.

$scope.modelName = $scope.optionType.Options[0];

使用ng-options代替ng-repeat可能会有所帮助.之所以有益的原因之一是ng-options不会创建子范围(与ng-repeat不同).这可以帮助简化与模型的链接并避免混淆.

It might be helpful to use ng-options instead of ng-repeat. One reason why it might be beneficial is that ng-options does not create a child scope (unlike ng-repeat). This could help simplify linking to your model and avoid confusion.

<select name="{{optionType.OptionTypeName}}" ng-model="modelName" ng-options="option for option in optionType.Options"> 
</select>

本文涵盖了ng-options的基础知识,并讨论了为何将其与ng-repeat相对使用.

This article covers the basics of ng-options as well as discusses why it would be used as opposed to ng-repeat.

希望这会有所帮助.

这篇关于动态选择列表默认选定项-Angular JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆