我正在構建一個使用Ionic Framework和Cordova Sqlite的移動應用程序。我正在離子列表中顯示來自sqlite數據庫的數據。每個離子列表項目都有一個按鈕來從數據庫中刪除相應的項目。點擊按鈕後,數據將從數據庫中刪除,但它會繼續顯示在離子列表中,直到我回到其他視圖並回到它。我需要立即刷新視圖,並從列表中刪除該項目。此外,我所有的SQL代碼都在控制器中,所以我似乎也需要重新加載控制器。在離子框架中重新加載視圖和控制器
app.js
.state('app.cart', {
url: '/cart',
views: {
'menuContent': {
cache: false,
templateUrl: 'templates/cart.html',
controller: 'NFController'
}
}
})
controller.js
.controller('NFController', ['$scope', '$cordovaSQLite','$cordovaToast','$state','$stateParams', function($scope, $cordovaSQLite, $cordovaToast, $state,$stateParams) {
$scope.listItems= [];
$cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
.then(
function(res) {
$scope.cartTotal=0;
$scope.crtPP=0;
if (res.rows.length > 0) {
for (var i=0; i<res.rows.length; i++) {
**$scope.crtPP=res.rows.item(i).productPrice*res.rows.item(i).productQuantity;
$scope.cartTotal=$scope.cartTotal+$scope.crtPP;
$scope.CProductName=res.rows.item(i).productName;
$scope.listItems.push(res.rows.item(i));**
}
}
else{
$scope.status = "No Products in the Cart";
}
},
function(error) {
$scope.statusMessage = "Error on loading: " + error.message;
}
);
$scope.remove = function(id) {
$cordovaSQLite.execute(db, 'DELETE from cart WHERE id=?', [id])
.then(function(res) {
//$state.go($state.current, {}, {reload: true});
var current = $state.current;
var params = angular.copy($stateParams);
$state.transitionTo(current, params, { reload: true, inherit: true, notify: true });
$cordovaToast.show('Removed from Cart','short','bottom');
}, function(error) {
console.log(error.message);
})
}
}])
刪除()被調用按鈕的點擊。
更新的代碼:
.controller('NFController', ['$scope', '$cordovaSQLite','$cordovaToast', function($scope, $cordovaSQLite, $cordovaToast) {
$scope.listItems= [];
$cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
.then(
function(res) {
$scope.cartTotal=0;
$scope.crtPP=0;
if (res.rows.length > 0) {
for (var i=0; i<res.rows.length; i++) {
$scope.listItems.push(res.rows.item(i));
}
cartTotal(); //cartTotal() called initially when the controller loads
console.log("Cart Total : " + $scope.cartTotal);
}
else{
console.log("####console######## NO results found #######"+"Table record #: ");
}
},
function(error) {
}
);
$scope.remove = function(id) {
$cordovaSQLite.execute(db, 'DELETE from cart WHERE id=?', [id])
.then(function(res) {
var index=$scope.listItems.indexOf(id)
$scope.listItems.splice(index,1);
cartTotal(); //CartTotal() called second time
$cordovaToast.show('Removed from Cart','short','bottom');
}, function(error) {
console.log(error.message);
})
console.log(id);
}
function cartTotal()
{
angular.forEach($scope.listItems, function(item, key) {
$scope.crtPP = item.productPrice * item.productQuantity;
$scope.cartTotal += $scope.crtPP;
console.log($scope.cartTotal);
});
}
}])
嘿@ LeftyX.Thank你的幫忙,夥計。我接受了答案。還有一個問題,如果你想幫忙。我剛更新了**下的控制器。我需要在我的視圖中顯示$ scope.cartTotal,這是通過db直接計算的。雖然,清單項目通過您的代碼消失,cartTotal不會得到更新。如何處理? – vkm
我已經更新了我的答案。希望能幫助到你。乾杯。 – LeftyX
Upvotes總是比歡迎:-)乾杯。 – LeftyX