$ resource响应AngularJS中的空数组

时间:2015-05-11 12:54:56

标签: javascript json angularjs resources

我想显示一个包含json数据项的表。我创建了一个服务来返回json数据。在我的Ctrl中,我正在查询服务以接收带有数据的数组。有点困惑。因为我将响应放在一个新的JS变量中,然后将JS变量放在一个范围变量中。我在我的html文件中使用了ngRepeat指令中的scope变量,然后它必须在表格中显示数据,但他们不会这样做。

服务:

myApp.factory('MyService', function ($resource) {
    return $resource('data/mydata.json');
});

控制:

var MyData = MyService.query(function () {
        $log.info('[Result:]', MyData); //console shows the expected data
    });

$scope.datas = MyData;
$log.info('Result2:', $scope.datas); //console shows an empty array

查看:

<tr ng-repeat="item in filteredData = (datas | filter:search)>
    <td>{{ item.id }}</td>
    <td>{{ item.name }}</td>
</tr>

通常数据必须包含在变量MyData中,不是吗?

编辑: 新的问题是,我的列表不会排序。我使用angularjs doc网站上的orderBy过滤器。

1 个答案:

答案 0 :(得分:4)

MyService.query....

async来电。 JS不会等待它的响应并执行下一行

$scope.datas = MyData;

因此你得到空数组。

将您的代码更改为:

var MyData = MyService.query(function () {
    $log.info('[Result:]', MyData); //console shows the expected data
    $scope.datas = MyData;
    $log.info('Result2:', $scope.datas);
});
相关问题