我正在研究一对Angular函数,当用户单击按钮时,它应该将值从false更改为true。该应用程序跟踪用户最喜欢的书籍;当用户创建收藏夹时,“跟踪”和“已完成”的默认值设置为false。当用户使用ng-click将它们更新为true时,新的“true”值不会修补到数据库,并且仍然在控制台中记录为false。对我的职能中缺少什么的想法?
$scope.trackFavorite = function(favorite) {
var favoriteParams = {
id: favorite.id,
tracking: favorite.tracking,
finished: favorite.finished
};
favorite.tracking = !favorite.tracking;
$http.patch("/api/v1/favorites/"+favorite.id+".json", favoriteParams).success(function(response) {
console.log("READING NOW");
console.log(response);
});
};
$scope.markFinished = function(favorite) {
var favoriteParams2 = {
id: favorite.id,
finished: favorite.finished,
};
favorite.finished = !favorite.finished;
console.log(favorite);
$http.patch("/api/v1/favorites/"+favorite.id+".json", favoriteParams2).success(function(response){
console.log("IS IT FINISHED");
console.log(response);
});
};
以下是视图中的ng-click代码段,以防万一:
<div>
<button ng-class="{tracking: favorite.tracking}" ng-click="trackFavorite(favorite)">Reading Now</button>
</div>
<div>
<button ng-class="{finished: favorite.finished}" ng-click="markFinished(favorite)">Finished</button>
</div>
非常感谢!
答案 0 :(得分:3)
您可能错过了一些http配置。正如这里已经注意到的那样:patch request using angularjs。
在控制器中实现错误功能也是一个好主意,例如根据响应更新表单。
$scope.trackFavorite = function(favorite) {
var favoriteParams = {
id: favorite.id,
tracking: favorite.tracking,
finished: favorite.finished
};
$http.patch("/api/v1/favorites/"+favorite.id+".json", favoriteParams)
.then(
function(response) {
console.log("READING NOW");
console.log(response);
//update the UI according to the response
favorite.tracking = !favorite.tracking;
},function(error){
//clean up when an error occurs
});
};