angularjs表单使用ng重复字段构建+;选择选项+$http.get

angularjs表单使用ng重复字段构建+;选择选项+$http.get,angularjs,ng-options,Angularjs,Ng Options,我有这样的代码: <form ng-controller="MyCtrl" ng-submit="save()> <div ng-repeat="f in fields"> <label for="theInput">{{ f.label }}</label> <select ng-model="f.value" ng-init="f.value = f.id" ng-options="item.id

我有这样的代码:

<form ng-controller="MyCtrl" ng-submit="save()>
    <div ng-repeat="f in fields">
        <label for="theInput">{{ f.label }}</label>
        <select ng-model="f.value" ng-init="f.value = f.id" ng-options="item.id as item.name for item in f.items"></select>
    </div>
</form>

<script>
    var Mod = angular.module('myApp', []);
    function MyCtrl($scope, $http) {
        var categories = [];
        $http.get(BASE_URL + 'task/listCategory').success(function(data) {
            categories = data;
        });
        $scope.fields = [
            { label: 'Category', value: 'items', items: categories }
        ];
    }
</script>
您可能需要执行以下操作

var Mod = angular.module('myApp', []);
    function MyCtrl($scope, $http) {
        var categories = [];
        $http.get(BASE_URL + 'task/listCategory').success(function(data) {
            categories = data;
            $scope.fields = [{ label: 'Category', value: 'items', items: categories }];
        });
    }

谢谢你的回答,但是我在表单中有不止一个字段,还有另一个解决方案吗?这里的问题是你的
http。get
的成功函数是一个异步调用。因此,如果在回调外部使用
数据
,则可能无法获取数据。所以我把作业放在了回调中。如果您遇到类似的问题,我认为这种技术可能会对您有所帮助。一种可能有效的方法是先创建空数组
$scope.fields=[]
,这样angular就会监视它…然后在成功的情况下将所有数据推送到空数组中当我填充
$scope.fields=[]
时,仍然不起作用,为什么?