如何使用 AngularJS 从 JSON 提要填充选择下拉列表? [英] How can I populate a select dropdown list from a JSON feed with AngularJS?

查看:26
本文介绍了如何使用 AngularJS 从 JSON 提要填充选择下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been looking hard for examples but could not find anything at all. The only thing I know is that I could use the http module to get my data. Here is what I am currently doing, but it's coded with Knockout. Can someone give me some advice on how I could recode this feature using 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>

推荐答案

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

The proper way to do it is using the ng-options directive. The HTML would look like this.

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

JavaScript:

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;
    });
});

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

You'll also need to ensure angular is run on your html and that your module is loaded.

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

这篇关于如何使用 AngularJS 从 JSON 提要填充选择下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆