ng-select with an object and its properties in angularjs

前端 未结 1 400
粉色の甜心
粉色の甜心 2021-02-02 17:26

I have been trying to figure out how to use an array if objects as the key values for an ng-select directive

this is the data I want to use

$scope.selec         


        
相关标签:
1条回答
  • 2021-02-02 17:50

    ng-options supports both array and object based data source. For example:

    Array based data source:

    $scope.options = ["Blue", "Red", "Yellow"]
    
    <select ng-model="selected"
            ng-options="for o in options">
    

    Object based data source:

    $scope.options = {
      "Blue": "color_1",
      "Red": "color_2",
      "Green": "color_3"
    }
    
    <select ng-model="selected"
            ng-options="name for (name, value) in options">
    

    However, you are using an incompatible data structure for the array based option. You can use like this:

    <select ng-model="selected"
            ng-options="o.name for o in options">
    

    and use the selected value as selected.value. (selected is bound to one of the objects in the array). This won't work if you want to submit the form via HTTP, so in this case you should convert the options to one of the data structure mentioned above.

    I've included these three usage here: http://plnkr.co/IEBQkqJNifY5MZWloDP6


    Edit: So I looked at the docs again today and found the way to work with your original data structure.

    <select ng-model="selected"
            ng-options="o.value as o.name for o in options">
    

    The plnkr is updated also.

    0 讨论(0)
提交回复
热议问题