下拉默认值根据条件选择

时间:2018-12-16 06:29:18

标签: angularjs select drop-down-menu

问题在这里dropdown issue with default selection 在用于填充下拉菜单的JSON下方。

//This is my jsf page
<h:panelGroup layout="block" id="panelBlock"> 
    <ui:repeat value="#{projectBean.projectList}" var="project">
        <h:outputText value="#{project.title}" />
        <h:outputText value="#{project.content}" />
    </ui:repeat>
</h:panelGroup>

<h:commandLink action="#{ProjectBean.save()}">
    <f:ajax execute="@form" render="panelBlock" />
</h:commandLink>

#This is my ViewScoped

private Project project
private List<Project> projectList;

@PostConstruct
private void init() {
  projectList = projectService.findAll();
}
# Setter and getter

public void save() {
   projectService.save(project)
}

#it works only after saving it i load the data from the database
public void save() {
   projectService.save(project)
   projectList = projectService.findAll();
}

下拉代码以显示项目

        {
            "key": "all",
            "value": "First",
            "default":"N"
        },       
        {
            "key": "only_my_events",
            "value": "Default",
            "default":"Y"
        },
        {
            "key": "only_assigned",
            "value": "Second",
            "default":"N"
        },
        {
            "key": "only_owner",
            "value": "Third",
            "default":"N"
        },
        {
            "key": "none",
            "value": "Fourth",
            "default":"N"
        }

必需

所选的默认项目应为默认值为Y(默认='Y')的项目。

问题。

下拉菜单中的第一项为空。没有默认选中的项目。

已经尝试过。

可见的解决方案,例如设置默认值,例如“选择一个项目”,这并不是我要找的。 AngularJS. When select have ng-model attribute, ng-selected not working

1 个答案:

答案 0 :(得分:1)

很简单,您只需将ng-model设置为 mail_notification

$scope.setDefault = function(){
  $scope.mail_notification = $scope.mail_notifications.find(t=>t.default === 'Y').key;
  console.log($scope.mail_notification);
}

和HTML

  <select ng-model="mail_notification" ng-options="c.key as c.value for c in mail_notifications" ng-init = "setDefault()"></select>

JSFIDDLE DEMO