这里是在 html 页面中按团队显示分组的静态代码。 我想要同样的过程使用mysql数据库记录。 anuglar Controller 和 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>
Controller
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);
最佳答案
假设您在 http::localhost/myapi/players
有一个后端服务,该服务返回其团队的玩家列表,即
[{name: 'Gene', team: { name: 'team alpha'}},
{name: 'George', team: {name: 'team beta'}},
...];
您可以使用 Angular $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
});
});
作为一种好的做法,您可以将服务器调用放在单独的服务中,例如,如果您有多个应调用同一服务的 View 和 Controller ,例如
app.factory('teamService', ['$http', function($http) {
var playerUrl = 'http::localhost/myapi/players';
return {
getTeamPlayers: function() {
return $http.get(playerUrl);
}
}
}]);
那么你的 Controller 是:
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了解详情。
注意:
您必须设置对 angular.filter 的依赖关系对于 groupBy
过滤器,您应该按 team.name
分组,而不仅仅是 team
。
我设置了 plunker其中后端服务是硬编码的。
关于php - 如何根据mysql数据库记录对angularjs中的记录进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41281664/