【发布时间】: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