我正在尝试从DB获取数据,并使用ng-repeat
显示它。来自工厂的getAll
函数正确地完成了这项工作,我得到了一个包含所有数据的对象,但它没有正确显示。在表中,我只得到第一个索引,后面什么也没有。
如果我尝试使用for(i = 0 ; i < DataService.persons.length ; i++)
,它工作得很好,但我不能将它与ng-repeat一起使用。
var testReactie = angular.module('testReactie', ['ngRoute']);
testReactie.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'instructiuni.ejs'
})
.when('/form', {
templateUrl : 'form.ejs',
controller : 'formContr'
})
.when('/test', {
templateUrl : 'joc.ejs',
controller : 'gameContr'
})
.when('/stat', {
templateUrl : 'scoruri.ejs',
controller : 'statContr',
resolve: {
postPromise:['DataService', function(DataService){
return DataService.getAll();
}]
}
});
});
testReactie.factory('DataService', ['$http', function($http) {
var o = {
persons:[],
person:{}
};
o.getAll = function(){
return $http.get('/db').success(function(data){
o.persons = data;
});
};
o.create = function() {
return $http.post('/db', o.person).success(function(data){
o.persons.push(data);
});
};
return o;
}]);
testReactie.controller('mainContr',function($scope) {
});
testReactie.controller('statContr',function($scope, DataService) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2>Scoruri</h2>
<table class="table">
<thead>
<tr>
<th>Nr.</th>
<th>Sex</th>
<th>Varsta</th>
<th>Timp Mediu</th>
</tr>
</thead>
<tbody>
<div ng-repeat = "pers in DataService.persons">
<tr>
<td>{{$index + 1}}</td>
<td>{{pers.sex}}</td>
<td>{{pers.varsta}}</td>
<td>{{pers.timp}}</td>
</tr>
</div>
</tbody>
</table>
</div>
发布于 2015-01-07 03:07:19
您不能将工厂作为控制器运行
在你的控制器中做类似这样的事情
testReactie.controller('mainContr', ['DataService', '$scope', function(DataService, $scope) {
DataService.getAll().then(function(successData){ // a promise helps you do something when it's resolved
$scope.awesomeData = successData;
}
});
将您的工厂的获取全部更改为如下所示
o.getAll = function(){
var promise = $q.defer(); // the $q helps create a promise
return $http.get('/db').success(function(data){
promise.resolve(data); // promise returns data when resolved
});
return promise; // returns a promise
};
您的模板应该是
<div ng-repeat = "pers in awesomeData">
这是因为当您的模板中有它时,它将自动调用$scope.awesomeData。所以当你有DataService的时候,它调用的是$scope.DataService,这是未定义的。
我希望这能帮到你。
发布于 2015-01-08 09:04:44
我解决了这个问题。它来自HTML。我在div中添加了ng-repeat指令,但它打破了这个表。在删除div并在标记中添加指令之后,它工作得很好。
https://stackoverflow.com/questions/27807952
复制相似问题