如何使用AngularJS从JSON源填充选择下拉列表?

Alan2 63 javascript angularjs drop-down-menu

我一直在努力寻找例子,但根本找不到任何东西.我唯一知道的是我可以使用http模块来获取我的数据.这是我目前正在做的事情,但它是用Knockout编码的.有人可以给我一些关于如何使用AngularJS重新编码此功能的建议吗?

HTML

<select id="testAccounts" 
   data-bind="options: testAccounts, optionsValue: 'Id', optionsText: 'Name', optionsCaption: 'Select Account', value: selectedTestAccount">
</select>

使用Javascript

<script type='text/javascript'>
    $(document).ready(function () {

        var townSelect = function () {
        var self = this;
        self.selectedTestAccount = ko.observable();
        self.testAccounts = ko.observableArray();
        var townViewModel = new townSelect();
        ko.applyBindings(townViewModel);

        $.ajax({
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 },
            type: 'GET',
            success: function (data) {
                townViewModel.testAccounts(data);
            }
        });
    });
</script>

Martin.. 149

正确的方法是使用该ng-options指令.HTML看起来像这样.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript的:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

您还需要确保在您的html上运行angular并且您的模块已加载.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

  • 这使我绊倒了; 所以我想我会在这里发表评论.如果未指定ng-model,则ng-options似乎没有影响.否则,+1; 谢谢你的回答. (12认同)

smk.. 35

<select name="selectedFacilityId" ng-model="selectedFacilityId">
         <option ng-repeat="facility in facilities" value="{{facility.id}}">{{facility.name}}</option>
     </select>  

这是一个如何使用它的示例.