大家好我正在为餐馆(学校项目)做CRUD,我可以显示我的API Rest中的所有元素,我可以删除元素,也可以创建新元素。但我的问题是我不知道如何更新元素。我正在使用$ resource更新,这是我的代码: 在这里,我显示我的菜肴,并在第一个按钮中显示2个按钮,我得到该元素的ID。
<tbody>
<tr ng-repeat = "dish in dishes | filter:sort">
<td>{{dish.name}}</td>
<td>{{dish.description}}</td>
<td>{{dish.price | currency}}</td>
<td>{{dish.category}}</td>
<td>
<button ng-click = "eliminarPlatillo(dish._id)" class = "glyphicon glyphicon-remove-circle btn btn-danger"></button>
<button ng-click = "modificarPlatillo(dish._id)" data-toggle = "modal" data-target = "#editarModal" class = "glyphicon glyphicon-pencil btn btn-success"></button>
</td>
</tr>
</tbody>
现在当我点击元素并得到它的id时,在一个模态中我放了新数据:
div id = "editarModal" class = "modal fade" role = "dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal">×</button>
<h4 class = "modal-title">Modificar Platillo</h4>
</div>
<div class = "modal-body">
<form role = "log" ng-submit = "modificarPlatillo()" ng-controller = "MenuController">
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "text" name = "name" id = "name" placeholder = "Nombre" class = "form-control" ng-model = "form.name">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "number" name = "price" id = "price" placeholder = "Precio" class = "form-control" ng-model = "form.price">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "text" name = "category" id = "category" placeholder = "Categoria" class = "form-control" ng-model = "form.category">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "file" name = "image" id = "image" placeholder = "Imagen" class = "form-control" ng-model = "form.image">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<textarea class = "form-control" placeholder = "Descripción" name = "description" id = "description" ng-model = "form.description" rows = "5" cols = "10"></textarea>
</div>
<div class = "form-group">
<button class = "btn btn-success" type = "submit">Aceptar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</div>
在ng-submit中,我调用我的函数来处理更新。 现在我的控制器是该功能:
$scope.modificarPlatillo = function(index) {
console.log($scope.index);
$scope.dish = menuService.getPlatillos().get({id:index});
console.log($scope.dish);
menuService.getPlatillos().update({id: index});
};
我说错了 PUT http://localhost:3000/api//platillos 404(Not Found),不知怎的,它是真的,因为删除你必须提供id的元素,但我在我的函数中这样做。
你们有解决我的问题的方法,如何使用模态并调用函数。
提前谢谢
编辑1:
MenuService:
use strict';
angular.module("nightshift")
.constant("baseURL", "http://localhost:3000/api/")
.service("menuService", ["$resource", "baseURL", function($resource, baseURL) {
this.getPlatillos = function() {
return $resource(baseURL + "/platillos/:id", null, {"update":{method:"PUT"}});
};
this.getPromociones = function() {
return $resource(baseURL + "/promociones", null, {"update":{method:"PUT"}});
}
}])
控制器:
"use strict";
angular.module("nightshift")
.controller("MenuController", ["$scope", "menuService", function($scope, menuService) {
var indice = 0;
$scope.dishes = menuService.getPlatillos().query(
function(response) {
$scope.dishes = response;
},
function(response) {
console.log("Error: " + response.statusText);
}
);
$scope.form = {name: "", description: "", price: "", category: "", image: ""};
$scope.agregarPlatillo = function() {
console.log($scope.form);
menuService.getPlatillos().save($scope.form);
$scope.form = {name: "", description: "", price: "", category: "", image: ""};
};
$scope.eliminarPlatillo = function(index) {
$scope.dish = menuService.getPlatillos().get({id:index});
console.log($scope.dish);
console.log(index);
menuService.getPlatillos().remove({id:index});
};
$scope.getIndex = function(index) {
indice = index;
}
$scope.modificarPlatillo = function(index) {
//console.log($scope.index);
//$scope.dish = menuService.getPlatillos().get({id:index});
//console.log($scope.dish);
menuService.getPlatillos().$save($scope.form);
};
}])
最后是Platillos.html,我调用我的函数并显示我的元素:
div id="wrapper">
<div id = "platilloModal" class = "modal fade" role = "dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal">×</button>
<h4 class = "modal-title">Alta de Platillos</h4>
</div>
<div class = "modal-body">
<form role = "log" ng-submit = "agregarPlatillo()">
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "text" name = "name" id = "name" placeholder = "Nombre" class = "form-control" ng-model = "form.name">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "number" name = "price" id = "price" placeholder = "Precio" class = "form-control" ng-model = "form.price">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "text" name = "category" id = "category" placeholder = "Categoria" class = "form-control" ng-model = "form.category">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "file" name = "image" id = "image" placeholder = "Imagen" class = "form-control" ng-model = "form.image">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<textarea class = "form-control" placeholder = "Descripción" name = "description" id = "description" ng-model = "form.description" rows = "5" cols = "10"></textarea>
</div>
<div class = "form-group">
<button class = "btn btn-success" type = "submit">Agregar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div id = "editarModal" class = "modal fade" role = "dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal">×</button>
<h4 class = "modal-title">Modificar Platillo</h4>
</div>
<div class = "modal-body">
<form role = "log" ng-submit = "modificarPlatillo()" ng-controller = "MenuController">
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "text" name = "name" id = "name" placeholder = "Nombre" class = "form-control" ng-model = "form.name">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "number" name = "price" id = "price" placeholder = "Precio" class = "form-control" ng-model = "form.price">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "text" name = "category" id = "category" placeholder = "Categoria" class = "form-control" ng-model = "form.category">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<input type = "file" name = "image" id = "image" placeholder = "Imagen" class = "form-control" ng-model = "form.image">
</div>
<div class = "form-group col-sm-10 col-sm-offset-1">
<textarea class = "form-control" placeholder = "Descripción" name = "description" id = "description" ng-model = "form.description" rows = "5" cols = "10"></textarea>
</div>
<div class = "form-group">
<button class = "btn btn-success" type = "submit">Aceptar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
Lista de Platillos
</h1>
<ol class="breadcrumb">
<li class="active">
<i class="fa fa-dashboard"></i> Platillos
</li>
</ol>
</div>
</div>
<div class = "row">
<div class = "col-sm-2">
<button type = "button" data-toggle = "modal" data-target = "#platilloModal" class = "btn btn-primary"><span class = "glyphicon glyphicon-plus-sign"></span> Agregar Platillo</button>
</div>
<div class = "pull-right form-group has-feedback">
<input type = "text" class = "form-control" placeholder = "Buscar Platillo" ng-model = "sort">
<span class = "glyphicon glyphicon-search form-control-feedback"></span>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Nombre</th>
<th>Descripción</th>
<th>Precio</th>
<th>Categoria</th>
<th>Acción</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "dish in dishes | filter:sort">
<td>{{dish.name}}</td>
<td>{{dish.description}}</td>
<td>{{dish.price | currency}}</td>
<td>{{dish.category}}</td>
<td>
<button ng-click = "eliminarPlatillo(dish._id)" class = "glyphicon glyphicon-remove-circle btn btn-danger"></button>
<button ng-click = "modificarPlatillo(dish._id)" data-toggle = "modal" data-target = "#editarModal" class = "glyphicon glyphicon-pencil btn btn-success"></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
尝试使用$.save
因为元素已经包含有关如何与API交互的信息,因此根据我的经验应该是最佳实践方法。是我使用的那个并且工作得很好。
编辑1: 这就是我通常处理API调用的方式(总是通过服务)
app.service('UsersService', function ($q, API) {
var self = {
'isLoading': false,
'editMode': false,
'list': [],
'selected': false,
'load': function () {
self.isLoading = true;
API.users.get().$promise.then(function (data) {
angular.forEach(data.list, function (user) {
self.list.push(new API.users(user));
});
self.isLoading = false;
});
}, 'create': function (user) {
var d = $q.defer();
API.users.save(user).$promise.then(function (data) {
self.list = [];
self.load();
d.resolve();
});
return d.promise;
}, 'read': function (id) {
for (var i = 0; i < self.list.length; i++) {
var obj = self.list[i];
if (obj.id == id) {
return obj;
}
}
}, 'update': function (user) {
var d = $q.defer();
user.$save({id: user.id}).then(function (data) {
for (var i = 0; i < self.list.length; i++) {
var obj = self.list[i];
if (obj.id == data.id) {
self.list[i] = data;
}
}
d.resolve();
});
return d.promise;
}, 'delete': function (user) {
var d = $q.defer();
user.$remove({id: contact.id}).then(function (data) {
for (var i = 0; i < self.list.length; i++) {
var obj = self.list[i];
if (obj.id == data.id) {
self.list.splice(i, 1);
}
}
self.selected = {};
d.resolve()
});
return d.promise;
}
};
self.load();
return self;
});
编辑2: 然后,只需注入服务并添加应用程序逻辑,就可以直接通过控制器使用它们(请注意这是我拥有的一个示例,它使用了您可能需要的附加模块和功能):
app.controller('UsersController', function ($stateParams, $translate, $state, $scope, $rootScope, ModalService, $element, UsersService, ClientsService, ngNotify) {
$scope.Users = UsersService;
$scope.Clients = ClientsService;
$scope.filterDirectory = "";
$scope.selectedClient = 0;
//Check if the state params have changed
if ($state.params.id > 0) {
$scope.$watch('Users.isLoading', function (n, o) {
if (!n) {
$scope.Users.selected = $scope.Users.read($state.params.id);
}
});
}
$scope.editUser = function (id) {
if (!angular.isUndefined(id)) {
$scope.Users.editMode = true;
} else {
$scope.Users.editMode = false;
$scope.Users.selected = "";
}
ModalService.showModal({
templateUrl: "app/views/users/editUser.modal.html",
controller: "UsersController"
}).then(function (modal) {
$scope.modal = modal;
$scope.modal.element.modal();
});
}
$scope.saveUser = function () {
if ($scope.Users.editMode) {
$scope.Users.update($scope.Users.selected).then(function (data) {
console.log(data);
ngNotify.set(($translate.instant('success_updated_saja')), {
type: 'success',
position: 'bottom',
duration: 1000
});
$element.modal('hide');
});
} else {
$scope.Users.create($scope.Users.selected).then(function (data) {
console.log(data);
ngNotify.set(($translate.instant('success_created_saja')), {
type: 'success',
position: 'bottom',
duration: 1000
});
$element.modal('hide');
});
}
}
$scope.removeUser = function () {
$scope.Users.delete($scope.Users.selected).then(function (data) {
$element.modal('hide');
$state.go("app.users");
});
}
$scope.selectClient = function (id) {
$scope.selectedClient = id;
}
$scope.filterList = function (contact) {
if ($scope.selectedClient != 0 && $scope.selectedClient != contact.client) {
return false;
}
if ($scope.filterDirectory) {
return contact.name.indexOf($scope.filterDirectory) == 0;
}
return true;
}
});
正如您所看到的,我通过获取(GET)它们来处理对象,然后推送它们(新的API),然后添加应该处理它们的函数。希望它有效
此致