用ajax和angular填充select选项

filling select option with ajax and angular

本文关键字:select 选项 填充 angular ajax      更新时间:2023-09-26

我有一个选择框,我想用从ajax文件中获得的数据填充,这是我的代码,但我没有在选择下拉列表中获得任何数据。

html:
    <select ng-model="selectedTestAccount" ng-options="item.Id as item.Name for item in testAccounts">
        <option value="">Profiles</option>
    </select>
js:
    angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
        method: 'GET',
        url: 'http://duda-api-test.herokuapp.com/profiles',
        data: { applicationId: 3 }
    }).success(function (result) {
    $scope.testAccounts = result;
});

});

您是否考虑使用指令?

.directive('mySelect', ['$scope','$http', function ($scope, $http) {
return {
    restrict: 'AE',
    replace: true,
    transclude: false,
    scope: { ngModel: '@'},      
    template: '<select "' +
                'ng-options="item.Id as item.Name for item in List">' +
                '<option value="">Profiles</option> ' +
              '</select>',
    link: function ($scope) {
    $http({
            method: 'GET',
            url: 'http://duda-api-test.herokuapp.com/profiles',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.List = result;
    }
};
}]);

html

<my-select ng-model="selectedTestAccount></my-select>

查看数据源时:

http://duda-api-test.herokuapp.com/profiles

你的ng选项是错误的。应该是:

ng-options="item.id as item.full for item in testAccounts"

你得到id&full,而不是Id和Name。