I'm trying to create a system in which I can display, edit and delete information on players and teams using angular along with a RESTful API. I have the parts working in which I show all the data and post data to the database.
The part I am having trouble with is updating data as I can't manage to get the http put working with the correct data being sent.
HTML
<script type="text/ng-template" id="team-single.html">
<div class="team-box">
<div class="badge">
<img ng-src="images/{{x.club_name}}.png" width="100" height="100"></div>
<div ng-hide="editorEnabled">
<div class="team-name">{{x.club_name}}</div>
<p><b>Manager:</b> {{x.club_manager}}</p>
<p><b>Ground:</b> {{x.club_ground}}</p>
<p><b>Nickname:</b> {{x.club_nickname}}</p>
<div class="team-p">{{x.club_info}}</div>
<a href="#" ng-click="editorEnabled=!editorEnabled">Edit Team</a>
</div>
<div ng-show="editorEnabled">
<p><input ng-model="x.club_name"></p>
<p><input ng-model="x.club_manager"></p>
<p><input ng-model="x.club_ground"></p>
<p> <input ng-model="x.club_nickname"></p>
<p><input ng-model="x.club_info"></p>
<input type="hidden" name="id" ng-value="" />
<a href="#" ng-click="editorEnabled=!editorEnabled; updateTeam($index)">Save</a>
</div>
</script>
<div class="row teams">
<div class="container">
<div class="col-md-4" ng-repeat="x in teams" ng-include="'team-single.html'"></div>
</div>
JS
var app = angular.module('footballApp', []);
app.controller("TeamCtrl", function ($scope, $http) {
$scope.updateTeam = function () {
$http({
method: 'PUT',
url: 'clubs.php/teams/' + id,
data: ??,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
};
});
I have enabled an editor on the front end to edit the fields. I don't know how to pass the one object being edited back into the updateTeam function while not passing the entire team array.
Also in the HTTP PUT, I have to use the id field of the relevant club in the URL but I'm not sure how to send this back.
Any help would be greatly appreciated.
答案 0 :(得分:1)
要解决您的问题,您可能需要重新考虑您的用户界面。为什么要在UI中一次为所有团队显示编辑选项。理想情况下,您应该显示团队详细信息以及编辑它们的选项。
当用户点击edit
时,调用包含team
数据的函数,然后显示一个表单,其中可以编辑这些详细信息,稍后可以发送以供提交。
请参阅此plnkr示例https://plnkr.co/edit/muqnmIhO77atLyEHS9y7?p=preview
<div class="row">
<div class="col-xs-6 col-lg-4" ng-repeat="team in teams">
<h2>{{ team.club_name }}</h2>
<p>{{ team.club_info }}</p>
<p><a class="btn btn-default" ng-click="onEditDetails(team)" href="javascript:void(0);" role="button">Edit details »</a></p>
</div>
</div>
然后在控制器中
$scope.onEditDetails = function(team) {
$scope.team = team;
};
这将为您提供当前所选团队的参考。您可以使用$scope.team
然后在用户界面中显示form
,可以将其与新编辑的数据一起提交。
注意:在您的示例中,您使用模板在UI中显示HTML,但由于它们位于ng-repeat
,因此每个模板都将使用last
变量循环。使用ng-include
包含的模板不会为team
中的每个teams
创建不同的范围。
如果您想创建可重复使用的HTML(虽然根据您的要求不必要),您可以创建directive并将其作为ng-repeat
<my-team-directive data="x"></my-team-directive>
中