Need example of select usage in AngularJS input form

后端 未结 3 767
礼貌的吻别
礼貌的吻别 2020-12-24 02:22

I am attempting to use an array of objects

 (array = [{name: \'Moe\', id:1}, {name: \'Larry\', id:2}, {name: \'Curly\', id:3}]) 

as a drop-

相关标签:
3条回答
  • 2020-12-24 02:53
    <select ng-model="choice">
        <option ng-repeat="obj in array" value="{{obj.id}}">{{obj.name}}</option>
    </select>
    

    or use 'ng-options' - http://docs.angularjs.org/api/ng.directive:select

    0 讨论(0)
  • 2020-12-24 02:56

    I would recommend using ng-options where you can.

    <select ng-model="choice" ng-options="x.id as x.name for x in array"></select>
    

    Because check this out: You can use it to select actual objects:

    app.controller('ExampleCtrl', function($scope) {
        $scope.items = [
            { id: 1, name: 'Foo' },
            { id: 2, name: 'Bar' }
        ];
    
        $scope.selectedItem = null;
    });
    
    <div ng-controller="ExampleCtrl">
        <select ng-model="selectedItem" 
                ng-options="item as item.name for item in items"></select>
    
        {{selectedItem | json}}
    </div>
    

    In the above example when you select something from the drop down, it's actually setting an entire object reference on selectedItem rather that just a value type.

    NOTE: using ng-options sets your value="" attributes to the indices of the items in your collections this is by design.

    It's really the best way to do it.

    EDIT: more context as requested. Also here's a plunker showing it in use

    0 讨论(0)
  • 2020-12-24 02:58
    <dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>
    
    
    <pre>selected roles = {{selected_items | json}}</pre>
    

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