以下是在html页面中按团队显示分组的静态代码。 我想要使用mysql数据库记录的相同进程。 anuglar控制器和Api需要进行哪些更改
HTML
<ul>
<li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
{{team}}
<ul>
<li ng-repeat="player in players">
{{player.name}}
</li>
</ul>
</li>
</ul>
控制器
app.controller('homeCtrl', function($scope) {
var teamAlpha = {name: 'team alpha'};
var teamBeta = {name: 'team beta'};
var teamGamma = {name: 'team gamma'};
$scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
{name: 'George', team: teamBeta},
{name: 'Steve', team: teamGamma},
{name: 'Paula', team: teamBeta},
{name: 'Scruath of the 5th sector', team: teamGamma}];
});
Php代码
$select=" select name, team from player where 1";
$result=$con->query($select)or die(mysqli_error());
$num=$result->num_rows;
if($num > 0)
{
$arr = array();
while($row=$result->fetch_array())
{
$arr[]=array('name'=>$row['name'],
'team'=>$row['team'],
);
}
}
$outputArr = array();
$outputArr['Player'] = $arr;
header("Content-type: application/json");
echo json_encode($outputArr);
答案 0 :(得分:1)
假设您在http::localhost/myapi/players
有一个后端服务,该服务返回一个包含其团队的玩家列表,即
[{name: 'Gene', team: { name: 'team alpha'}},
{name: 'George', team: {name: 'team beta'}},
...];
您可以使用有角度的$http
服务来调用后端:
app.controller('homeCtrl', function($scope, $http) {
var playerUrl = 'http::localhost/myapi/players';
$http.get(playerUrl).then(function(response) {
$scope.teamPlayers = response.data;
}, function(responseError) {
// do something if backend return an error
});
});
作为一种良好做法,您可以将服务器调用放在单独的服务中,例如,如果您有多个视图和控制器,它们将调用相同的服务,例如
app.factory('teamService', ['$http', function($http) {
var playerUrl = 'http::localhost/myapi/players';
return {
getTeamPlayers: function() {
return $http.get(playerUrl);
}
}
}]);
然后您的控制器是:
app.controller('homeCtrl', ['$scope', 'teamService', function($scope, teamService) {
teamService.getTeamPlayers().then(function(response) {
$scope.teamPlayers = response.data;
}, function(responseError) {
// do something if backend return an error
});
}]);
$http
服务是异步的,并返回promise
,因此使用.then(function(response) {...});
。有关详细信息,请参阅$http documentation。
注意:
您必须为groupBy
过滤器设置angular.filter的依赖关系,并且team.name
不仅要team
分组。
我设置了plunker后端服务是硬编码的。
答案 1 :(得分:0)
控制器:
var teamAlpha = {name: 'team alpha'};
var teamBeta = {name: 'team beta'};
var teamGamma = {name: 'team gamma'};
$scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
{name: 'George', team: teamBeta},
{name: 'Steve', team: teamGamma},
{name: 'Paula', team: teamBeta},
{name: 'Scruath of the 5th sector', team: teamGamma}];
视图:
<ul ng-repeat="(team, value) in teamPlayers | groupBy: 'team.name'">
Group name: {{ team }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>