这是我在index.html中使用的组件gamesGrid的模板。在这个模板的内部,我有一个表格,我想要使用ng-repeat,但它不起作用。
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Title</th>
<th>Platform</th>
<th>Score</th>
<th>Genre</th>
<th>Editor's Choice</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="detail in gamesDetails">
<td>{{detail.title}}</td>
</tr>
</tbody>
</table>
</div>
这是我的component.js文件
(function() {
'use strict';
angular.module('myApp').component('gamesGrid', {
templateUrl: './components/games-grid.view.html',
controller:'gamesGridController'
});
})();
这是我的controller.js文件
angular.module('myApp').controller('gamesGridController',function(gridDataFactory) {
this.$onInit = function() {
};
this.$postLink = function() {
this.gamesDetails = [];
gridDataFactory.fetchUserDetails().then(function(response) {
this.gamesDetails = response;
console.log(this.gamesDetails);
});
}
});
这是我的工厂:
angular.module('myApp').factory('gridDataFactory', function($http) {
var gameDetails = [];
var obj = {};
obj.fetchUserDetails = function(){
return $http.get('http://starlord.hackerearth.com/gamesarena').then(function(response) {
gameDetails = response.data;
gameDetails.shift();
return gameDetails;
});
}
return obj;
});
正如您所看到的,我在模板中使用了ng-repeat,但它无效,我无法在视图中看到任何数据。
答案 0 :(得分:2)
您正在使用 this.gamesDetails
,因此请将您的视图更改为使用 controller syntax
,如下所示。
<div class="container" ng-controller="gamesGridController as ctrl">
<table class="table table-hover">
<thead>
<tr>
<th>Title</th>
<th>Platform</th>
<th>Score</th>
<th>Genre</th>
<th>Editor's Choice</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="detail in ctrl.gamesDetails">
<td>{{detail.title}}</td>
</tr>
</tbody>
</table>
</div>
答案 1 :(得分:1)
this.$postLink = function() {
this.gamesDetails = [];
gridDataFactory.fetchUserDetails().then(function(response) {
$scope.gamesDetails = response;
console.log(this.gamesDetails);
});
}
在这段代码中,我看到你已经分配了this.gameDetails,这在范围内是不可用的。使用$ scope.gameDetails将其绑定到视图。