在angular -s的ng-options中解析对象,使用嵌套的json选择下拉列表

时间:2014-10-15 00:21:18

标签: javascript angularjs angularjs-ng-options angularjs-ng-model

我有以下json:

  [
{
    "normal" :{
        "font": "Burlington Script.ttf",
        "fontFamily": "sf_burlington_scriptregular",
        "fontName": "Burlington Script"
    },
    "bold" : {
        "font": "SF_Burlington_Script_Bold.ttf",
        "fontFamily": "sf_burlington_scriptbold",
        "fontName": "Burlington Script"
    },
    "italic" : {
        "font": "SF_Burlington_Script_Italic.ttf",
        "fontFamily": "sf_burlington_scriptitalic",
        "fontName": "Burlington Script"
    },
    "bold-italic": {
        "font": "SF_Burlington_Script_Bold_Italic.ttf",
        "fontFamily": "sf_burlington_scriptBdIt",
        "fontName": "Burlington Script"
    }

},

{
    "normal" :{
        "font": "Some_Script.ttf",
        "fontFamily": "Some_scriptregular",
        "fontName" : "Some Script"
    },
    "bold" : {
        "font": "Some_Script_Bold.ttf",
        "fontFamily": "Some_scriptbold",
        "fontName" : "Some Script"
    },
    "italic" : {
        "font": "Some_Script_Italic.ttf",
        "fontFamily": "Some_scriptitalic",
        "fontName" : "Some Script"
    },
    "bold-italic": {
        "font": "Some_Script_Bold_Italic.ttf",
        "fontFamily": "Some_scriptBdIt",
        "fontName" : "Some Script"
    }

}
]

我想要做的是只在“正常”下的下拉列表中显示fontName,并将值设置为fontFamily。

我试过了

 <select                
      ng-model="selectedFont"
      ng-options="fonts as fonts.normal.fontName for fonts in designFonts" required>
 </select>

但没有运气。我在我的控制器中将$ scope.designFonts设置为json。

1 个答案:

答案 0 :(得分:2)

您可以利用ng-option expressionselect as部分来设置选择选项时设置ng-model值所需的内容。所以fonts.normal.fontFamily as fonts.normal.fontName for fonts in designFonts并使用跟踪方式将选项值设置为相应的值( track by始终应用于值)。

尝试: -

  <select                
     ng-model="selectedFont"
     ng-options="font as font.normal.fontName for font 
                   in designFonts track by font.normal.fontFamily" 
  required></select>

<强> Demo

如果您使用font.normal.fontFamily as font.normal.fontName,如果您需要将整个对象作为ng-model,则会使用相应的fontFamily设置ng-model,然后使用您现在拥有的方式。


有一个可能的ng-select错误,虽然select as已被应用,但您不能将track byng-model一起用于导致选择问题的相同字段。所以你可以使用: -

 ng-options="font as font.normal.fontName for font 
                   in designFonts track by font.normal.fontFamily" 

但你不能

 ng-options="font.normal.fontFamily as font.normal.fontName for font 
                   in designFonts track by font.normal.fontFamily"