我正在开发一个使用 Mongo 作为 DB 和 Java 的 Angular 应用程序。
当我单击获取数据按钮时,我正在尝试从 mongo DB 中获取数据,请参见 js bin http://jsbin.com/aRuWInU/2/edit中的代码,对于我的 html 页面,请参见代码下方:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="/angular.js"></script>
<script src="myscript.js"></script>
<meta charset=utf-8 />
<title>Demo</title>
</head>
<body ng-controller="MyApp">
<!--It will fetch data from Mongo Using REST service through
the angular factory ConsumptionEngineRESTService-->
<button type="button" ng-click="getAllData()">Get Data</button>
<h1>My Demo With filter</h1>
<div ng-repeat="Maindata in myFilteredKey" class="">
<h2>{{Maindata}}</h2>
<div ng-repeat="item in data | filter:{'key':Maindata}">
<p>My key is {{item.key}}</p>
<p>My val is {{item.value}}</p>
</div>
</div>
</body>
</html>
当我从 REST 服务获取数据时发生问题,延迟获取数据导致我出现问题,例如 $scope.data 未填充但在下面的 for 循环中用于填充 $scope.myFilteredKey 数组,所以我的 $scope .myFilteredKey 数组为空。查看 myscript.js 的代码
myscript.js
var app = angular.module('myapp', []);
app.controller('MyApp', ['$scope', function($scope,ConsumptionEngineRESTService) {
$scope.getAllData=function(){
console.log("hi");
/*STUB Data: when it is used , code is working perfectly*/
/* $scope.data = [
{key:"home",value:"hk1"},
{key:"home",value:"hk2"},
{key:"home",value:"hk3"},
{key:"home",value:"hk4"},
{key:"product",value:"pk1"},
{key:"product",value:"pk2"},
{key:"product",value:"pk3"},
{key:"product",value:"pk4"},
{key:"service",value:"sk1"},
{key:"service",value:"sk2"},
{key:"service",value:"sk3"},
{key:"service",value:"sk4"}
]; */
/* Data From REST Service: Issue happens when i fetch data from REST service,
*Delay in fetching data cause me the issue, such as $scope.data is not populated but
*that is used in the below for loop to populate the $scope.myFilteredKey array*/
/*ConsumptionEngineRESTService is a angular factory. uses REST service to fetch from Mongo*/
$scope.data =ConsumptionEngineRESTService.getAll();
$scope.myFilteredKey=[];
for(i=0;i<$scope.data.length;i++){
if($scope.myFilteredKey.indexOf($scope.data[i].key)==-1){
$scope.myFilteredKey.push($scope.data[i].key);
console.log($scope.data[i].key);
}
}
}
}]);
请帮我解决这个问题,我想在 for 循环执行时填充 $scope.data,因为 for 循环正在使用 $scope.data。注意:对于这个问题,我没有包括 REST 服务 angular factory ConsumptionEngineRESTService
。
app.factory("ConsumptionEngineRESTService ", function($resource, $http) {
var resource = $resource("/rest/:ID ", { ID : "@_ID " },
{
'create': { method: 'POST' },
'getAll': { method: 'GET', isArray: true },
'get': { method: 'GET', isArray: false },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
}
);
return resource;
});
请帮助我。谢谢提前提供任何帮助。