Parsing object in ng-options for angularjs select

2019-08-27 21:56发布

问题:

I have the following 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"
    }

}
]

what i want to do is display the fontName in the drop down under "normal" only and have the value be fontFamily.

I have tried

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

but no luck. i am setting $scope.designFonts in my controller to whatever the json is.

回答1:

You can utilize the select as part of the ng-option expression to set what you need to set the value of the ng-model when an option is selected. So fonts.normal.fontFamily as fonts.normal.fontName for fonts in designFonts and use a track by to have the option value set with respective value (track by is always applied to value).

Try:-

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

Demo

If you use font.normal.fontFamily as font.normal.fontName will set ng-model with the respective fontFamily if you need the entire object as ng-model then use the way you have now.


Well there is a possibly ng-select bug, you cannot use select as with track by together on the same field which causes issue in selection, though ng-model gets applied. So you could use:-

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

But you can't

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