一切正常,但我在从服务获取源代码时遇到问题。
我有下面的服务代码。
app.factory('myService',
function($rootScope, ResourceData) {
var result = {};
var data = ResourceData.query();
result.getData = function() {
// problem here
}
return result;
});
并且CONTROLLER包含代码。
app.controller('myController', ['$scope', 'myService',
function myController($scope, myService) {
$scope.data = myService.getData();
});
我的问题是我的服务中是否有这样的功能
result.getData = function() {
return data;
}
一切正常,但我需要在获取数据之前过滤该数据
如果我像这样改变主体,我会得到一个空数组,问题似乎是来自 AngularJS。
如果我创建静态数组,它就可以工作。
result.getData = function() {
var arr = [];
angular.forEach(data, function(item, key) {
// simple filter
if(item.ID > 10) {
return;
}
else {
arr.push(item);
}
});
return arr;
}
最佳答案
“ResourceData.query()”的结果是异步的:
When the data is returned from the server then the object is an instance of the resource class... It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
当页面首次加载时,我猜测 Controller 在从服务器返回数据之前运行,因此第一次调用 getData() 时,data
可能尚未填充任何数据,所以你得到一个空数组。
解决您的问题的一种方法是使用 Angular 过滤器来过滤 View /HTML 中的数据,而不是在服务中。
<div ng-repeat="item in data | filter:myFilter">
{{item.ID}}: {{item...}}
</div>
然后在你的 Controller 中:
$scope.myFilter = function(item) {
return item.ID <= 10;
}
关于javascript - AngularJS 从服务返回资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14112552/