【问题标题】:In AngularJS, $http doesn't change my select option tag data在 AngularJS 中,$http 不会更改我的选择选项标签数据
【发布时间】:2016-08-15 21:22:52
【问题描述】:

我在 AngularJS 中有一个关于使用 $http 从服务器获取数据的问题。 这是我的 HTML

<select ng-model="foo" ng-options="item as item.name for item in items"></select>

这是我的 AngularJS 脚本

angular.module("myApp").controller("myCtrl", function($scope, $http) {
    var $scope.items = [];
    $scope.items = [
        {
            "id": 1,
            "name": "item1"
        },
        {
            "id": 2,
            "name": "item2"
        },
    ];

    getData();

    function getData() {
        $http.get("ng/getData")
            .then(function(response) {
                if (response.status == 200) {
                    $scope.items = response.items;
                    /*
                    $scope.items = [
                        {
                            "id": 5,
                            "name": "item11"
                        },
                        {
                            "id": 4,
                            "name": "item22"
                        }
                    ];
                    */
                }
            });
    }
});

此代码的预期是当 $http 从服务器获取数据时,选择下拉数据将发生变化。但这并没有改变任何东西。我还在成功回调中的控制台中打印了响应项。

也许我不太了解 $http 的用法。也许当我在 getData(); 之后控制台输出数据时$scope.items 根本没有改变。而且我认为 $http 可能总是在最后阶段运行。

谁能帮忙解释一下这个问题?如果我的假设是正确的,我正在寻找的解决方案是什么?

【问题讨论】:

  • 你检查过你是否传入了then 回调吗?此外,来自响应的数据存储在response.data 下,因此您应该拥有$scope.items = response.data.item

标签: angularjs angularjs-scope angularjs-http angularjs-ng-options


【解决方案1】:

我认为您只需添加一个track by 子句:

ng-options="item as item.name for item in items track by item.id"

【讨论】:

    【解决方案2】:

    检查响应对象。当您使用“then”回调来获取解析的数据时,实际的 API 结果将存储在响应的“data”属性中。所以把你的代码改成

    $scope.items = response.data;
    

    或者您可以使用成功回调直接附加数据。

            $http.get("ng/getData")
                .success(function(response) {
                    if (response.status == 200) {
                        $scope.items = response.items;
                    }
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 2015-06-19
      • 2021-08-24
      相关资源
      最近更新 更多