I created a live pool app where you can create, view and delete questions from the table pools from the rethinkdb database.
The delete is the problem. When I use a DELETE request with POSTMAN, it works, the table is deleted. But when I click on the delete button in Angular, it doesn't do anything. How do I create a DELETE http request ?
This is my delete code that works in the database:
deletePolls(pollData,callback) {
async.waterfall([
function(callback) {
var pollObject = new db();
pollObject.connectToDb(function(err,connection) {
if(err) {
return callback(true,"Error connecting to database");
}
callback(null,connection);
});
},
function(connection,callback) {
//THIS DELETES THE TABLE FROM THE DATABASE
rethinkdb.table('poll').delete().run(connection,function(err,result) {
connection.close();
if(err) {
return callback(true,"Error happens while deleting polls");
}
callback(null,result);
});
}
],function(err,data) {
callback(err === null ? false : true,data);
});
}
This is the button in my index.html, that calls the function delete():
<md-button ng-submit="delete()">Delete the table</md-button>
This is the function that should delete:
$scope.delete = function() {
$http.delete("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
console.log("IvanUspeh");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
});
};
Here is the full app.js, the javascript that angular works with:
var app = angular.module('starterApp', ['ngMaterial','ngRoute','ngMessages']);
app.factory('socket',function(){
var socket = io.connect('http://localhost:3000');
return socket;
});
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'home.html'
})
.when('/create',{
templateUrl: 'create.html'
})
.when('/view',{
templateUrl: 'view.html'
})
.when('/delete',{ //IGNORE THIS, THIS JUST OPENS AN EMPTY HTML
templateUrl: 'delete.html'
})
;
});
app.controller('pollingController',function($scope,$mdDialog,$http,socket) {
$scope.pollData = [];
$scope.formData = {};
$scope.voteData = {};
$scope.hiddenrows = [];
getPollData();
function getPollData() {
$http.get("/polls").success(function(response){
$scope.pollData = response.data;
});
}
$scope.submitPoll = function(ev) {
var data = {
"question" : $scope.formData.pollQuestion,
"polls" : [{
"option" : $scope.formData.pollOption1, "vote" : 0
},{
"option" : $scope.formData.pollOption2, "vote" : 0
},{
"option" : $scope.formData.pollOption3, "vote" : 0
}]
};
var message = {"title" : "", "message" : ""};
$http.post('/polls',data).success(function(response) {
if(response.responseCode === 0) {
message.title = "Uspeh !";
message.message = "Anketa je uspešno napravljena.";
data["id"] = response.data.generated_keys[0];
$scope.pollData.push(data);
} else {
message.title = "Greška !";
message.message = "Greška u toku pravljenja ankete.";
}
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title(message.title)
.textContent(message.message)
.ok('Got it!')
.targetEvent(ev)
);
});
}
$scope.updateVote = function(index) {
var data = {
"id" : $scope.pollData[index].id,
"option" : $scope.pollData[index].selected
};
$http.put("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
});
}
$scope.delete = function() {
$http.delete("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
console.log("IvanUspeh");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
});
};
socket.on('changeFeed',function(data) {
for(var pollCounter = 0 ;pollCounter < $scope.pollData.length; pollCounter++) {
if($scope.pollData[pollCounter].id === data.id) {
$scope.pollData[pollCounter].polls = data.polls;
$scope.$apply();
}
}
});
});
So, when I push the button with the function delete(), I want it to delete everything in the table like in POSTMAN, like a http request. What am I doing wrong ?
This is not much of a solution , rather a suggestion on how to debug
You are capturing only the success from the http call but not the error . You can write the function like below to more detail on where its failing.
$scope.delete = function() {
console.log("delete function called");
$http.delete("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
console.log("IvanUspeh");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
})
.error(function (data, status, header, config) {console.log(status)});
};
Related
I have some trouble trying to get this script working!
In my route, I have these lines of code:
.state('app.subcats', {
cache: false,
url: '/subcat/:idcat',
views: {
'menuContent#app': {
templateUrl: 'client/templates/shop/subcat.html',
controller: 'SubcatsCtrl as vm'
}
}
})
Here is the script subcat.js:
import { _meteorAngular } from 'meteor/angular';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
angular
.module('salephone')
.controller('SubcatsCtrl', SubcatsCtrl);
function SubcatsCtrl (
$scope,
$stateParams,
$state,
$reactive,
$rootScope,
$ionicLoading,
$ionicHistory,
$ionicViewSwitcher,
$timeout
){
$reactive(this).attach($scope);
console.log("test");
var self = this;
this.subcats = [];
this.contentLoaded = false;
self.noPosts = "";
if( window.localStorage.getItem('subcats') ){
this.productss = JSON.parse( window.localStorage.getItem('subcats') );
}
//Variables for infinite scroll.
self.loaded = 100;
self.limit = self.loaded;
console.log("test 1");
this.getSubcat = function(){
//Load products on scroll.
this.subscribe('SubcatMain', () => [ $stateParams.idcat, self.loaded ], {
onReady: function() {
//Get count of all Products in server.
//Method is located at tapshop/lib/methods/app_methods.js
Meteor.call('allSubcats', $stateParams.idcat, function(err, count) {
self.allsubcats = count;
self.limit = self.loaded;
self.subcats = Products.find({
catLinkID : $stateParams.idcat,
listingsCount: { $gt: 0 }
},{
sort: {
productOffersCount: -1,
listingsCount: -1,
name: 1
},
limit: self.limit
}).fetch();
window.localStorage.setItem('subcats', JSON.stringify(self.subcats) );
self.contentLoaded = true;
self.noPosts = 'No posts available.';
$ionicLoading.hide();
return;
});
},
onStop: function(err){
console.log("test 2");
if(err){
self.contentLoaded = true;
self.noPosts = "No internet connection.";
console.log(JSON.stringify(err)); // <- nothing here
return;
}
}
});
}
this.getSubcat();
...
When I launch the script, I get only:
No internet connection.
Nothing about the error message! And, I see no place in which I made an error!
Could someone give me any idea of the problem, please?
I am working on IONIC V1 + METEOR.
Notice that nothing returned from the database as well!
I am trying to add a service to eliminate some code that I have been repeating through my app.
The service:
/* --------------------------------------------------------------
---------- FUNCTIONS FOR PAGE ALERTS THROUGHOUT Project-------
---------------------------------------------------------------*/
angular.module('app').service('PageAlertService', function () {
this.setAlert = function() {
console.log("In setAlert");
if (localStorage.getItem("Success")) {
var alertObj = {
alert: "Success",
alertMessage: localStorage.getItem("Success")
};
} else if (localStorage.getItem("Error"){
var alertObj = {
alert: "Error",
alertMessage: localStorage.getItem("Error")
};
};
return alertObj;
};
this.errorStatusCheck = function(error, successString) {
if (error.status = -1) {
localStorage.setItem("Success", successString);
} else {
localStorage.setItem("Error", "Error occured: " + error.status + error.statusText);
};
};
});
but whenever I try to add it to any of my controllers I'd like to use it in it breaks my angular web app and gives me the
Error: $injector:unpr
Unknown Provider
Here is my app.js:
var app = angular.module('app',
[
'JobCtrl',
'JobSvc',
'WebsiteCtrl',
'WebsiteSvc',
'myClientCtrl',
'ClientSvc',
'MediaCompanyCtrl',
'MediaCompanySvc',
'PageAlertSvc',
'ui.bootstrap',
'ui.bootstrap.tpls'
]
);
Here is my controller:
/* --------------------------------------------------
-------- Media Jobs Controller ----------------------
--------------------------------------------------- */
angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.controller('JobCtrl',
[
'JobService',
'WebsiteService',
'MediaCompanyService',
'ProductService',
'$scope',
'$uibModal',
'PageAlertService',
function (JobService, WebsiteService, MediaCompanyService,
ProductService, $scope, $uibModal, $uibModalInstance, PageAlertService)
{
/* ------------------------------------
--------- Variables -----------------
-------------------------------------*/
$scope.mediaCompanies = {};
$scope.websites = {};
$scope.products = [];
$scope.selectedProducts = [];
$scope.isSelected = false;
$scope.new = {
Job: {}
};
/* ----------------------------------------------------------------
--- INITIALIZE LISTS OF JOBS, WEBSITES, COMPANIES, AND PRODUCTS ---
------------------------------------------------------------------*/
/* Get Jobs Initialization */
function getJobs() {
JobService.getJobs()
.then(
function (data) {
$scope.total_count = data.JobCount;
$scope.model = data.mediaJobList;
},
function (errResponse) {
console.log("Error while getting jobs");
});
};
getJobs();
/* Get Websites Initialization */
function getWebsites() {
WebsiteService.getWebsites()
.then(
function (data) {
$scope.websites = data;
},
function (errResponse) {
console.log(errResponse);
});
};
getWebsites();
/* Get Companies Initialization */
$scope.getCompanies = function () {
MediaCompanyService.getCompanies()
.then(
function (data) {
$scope.mediaCompanies = data;
},
function (errResponse) {
console.log(errResponse);
});
};
$scope.getCompanies();
/* Get Products -- passing website id*/
$scope.getProducts = function (webid) {
ProductService.getProducts(webid)
.then(
function (data) {
$scope.selectedProducts = data.MediaProductList;
},
function (errResponse) {
console.log(errResponse);
});
};
/* ----------------------------------------------------------------
----------- STILL NEED TO FIGURE OUT WHAT TO DO WITH YOU ----------
------------------------------------------------------------------*/
///* Shows Success and Error Alerts - Maybe make into a directive or
// Service? */
//if (localStorage.getItem("Success")) {
// $scope.alert = "Success";
// $scope.alertMessage = localStorage.getItem("Success");
// localStorage.clear();
//} else if (localStorage.getItem("Error") && localStorage.getItem("Error") !== null) {
// //sometimes get errors even when adding, deleting, updating is successful
// $scope.alert = "Error";
// $scope.alertMessage = localStorage.getItem("Error");
// localStorage.clear();
//};
if (localStorage.getItem("Success") != null || localStorage.getItem("Error") != null) {
console.log("I'm In")
var alert = {};
alert = PageAlertService.setAlert();
//$scope.alert = alert.alert;
//$scope.alertMessage = alert.alertMessage;
localStorage.clear();
}
/* -----------------------------------
------ JOB CRUD FUNCTIONS ----------
-------------------------------------*/
/* Add Job - Also Adds Products to Database */
$scope.addJob = function () {
var successString = "Added Job Succesfully!";
JobService.addJob($scope.new.Job).then(
function (success) {
localStorage.setItem("Success", successString);
},
function (error) {
//if (error.status = -1 && error.status !== 500) {
// localStorage.setItem("Success", successString);
//} else {
// localStorage.setItem("Error", "Error while adding Job! " + error.status + ":" + error.statusText);
//}
PageAlertService.errorStatusCheck(error, successString);
});
//adds products after adding job
addProducts();
location.reload();
}
/* Update Job -- Also Updates Products in Database */
$scope.updateJob = function (job) {
var successString = "Updated Job Succesfully!";
JobService.updateJob(job).then(
function (success) {
localStorage.setItem("Success", successString);
},
function (error) {
//if (error.status = -1 && error.status !== 500) {
// localStorage.setItem("Success", successString);
//} else {
// localStorage.setItem("Error", "Error while updating job! " + error.status + ":" + error.statusText);
//}
PageAlertService.errorStatusCheck(error, successString);
}
);
updateProducts();
location.reload();
}
/* Delete Job */
$scope.deleteJob = function (job) {
var successString = "Deleted Job Succesfully!";
var indx = $scope.model.indexOf(job);
JobService.deleteJob(job.Id).then(
function (success) {
localStorage.setItem("Success", successString);
},
function (error) {
//if (error.status = -1 && error.status !== 500) {
// localStorage.setItem("Success", successString);
//} else {
// localStorage.setItem("Error", "Error occured while deleting job! " + error.status + ":" + error.statusText);
//}
PageAlertService.errorStatusCheck(error, successString);
}
);
location.reload();
}
/* Run Job */
$scope.runJob = function (id, d1, d2) {
$scope.runButtonText = "Running";
//format Date
var date1 = $scope.FormatDate(d1);
var date2 = $scope.FormatDate(d2);
JobService.runJob(id, date1, date2).then(
function (success) {
$scope.runButtonText = "Finished";
},
function (error) {
if (error.status = -1 && error.status !== 500) {
$scope.runButtonText = "Finished";
} else {
$scope.runButtonText = "Error Occured";
console.log(error);
}
});
}
/* ----------------------------------------------------
---------- PRODUCT CRUD FUNCTIONS ---------------------
------------------------------------------------------*/
var addProducts = function () {
ProductService.addOrUpdate($scope.products).then(
function (response) {
console.log(response);
},
function (err) {
console.log(err);
});
};
var updateProducts = function () {
ProductService.addOrUpdate($scope.selectedProducts).then(
function (response) {
console.log(response);
},
function (err) {
console.log(err);
});
};
var deleteProducts = function (product) {
ProductService.deleteProduct(id).then(
function (response) {
console.log(response);
},
function (err) {
console.log(err);
});
};
/* ----------------------------------------------
--------- Code to Manipulate View Model --------
----------------------------------------------*/
/* Toggles Active Toggle Button */
$scope.updateActive = function (job) {
job.Active = !job.Active;
setTimeout(function () {
}, 500);
this.updateJob(job);
}
/* Selects Job and and Gets Product List */
$scope.selectJob = function (job) {
$scope.isSelected = true;
$scope.goToJobSection = false;
$scope.goToEditSection = true;
$scope.selectedJob = {}
$scope.selectedJob = job;
//selects product list by webid
var websiteId = $scope.selectedJob.WebsiteId;
$scope.getProducts(websiteId);
}
/* Onclick Event to stop people from
adding products to database with different
website ids*/
$scope.remProdOnClick = function () {
var newList = [];
if ($scope.goToEditSection == false) {
$scope.products = [];
}
}
/* ----------------------------------------------------------
--- MODAL -- May need to bring this out into a Directive ----
-----------------------------------------------------------*/
/* Shows Modal */
$scope.showModal = function (action, obj) {
$scope.$modalInstance = $uibModal.open({
scope: $scope,
inputs: {
title: action + " Job"
},
restrict: "E",
templateUrl: 'app/modal/JobModals/modal' + action + 'Template.html',
controller: "JobCtrl",
backdrop: 'static',
keyboard: false
});
}
/* Exits Modal */
$scope.exitModal = function () {
$scope.$modalInstance.dismiss('cancel');
};
}]);
I cannot seem to figure out why this is occurring. All my other services are working perfectly.
Thanks!
On your controller declaration, you inject 7 dependencies, but you have 8 as arguments, you are either forgetting to inject one dependency or to delete one argument.
angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.controller('JobCtrl',
[
'JobService',
'WebsiteService',
'MediaCompanyService',
'ProductService',
'$scope',
// missing dependency here
'$uibModal',
'PageAlertService',
function (JobService, WebsiteService, MediaCompanyService,
ProductService, $scope, $uibModal,
$uibModalInstance // or extra dependency here
, PageAlertService)
{
...
}
I tried multiple solutions but the only thing that seemed to work was by putting my service into the folder with all my other services. Once it was moved I no longer got the $injector error I was talking about above.
/MainProject
-/app
-/Common
-/Controllers
JobCtrl.js
OtherCtrl.js
-/Services
JobSvc.js
PageAlertSvc.js
OtherSvs.js
-/Modal
-/Templates
-/Vendor
app.js
As you can see instead of putting the PageAlertSvc.js in Common I had to put it in the Services folder.
In your controller, you should not need to redefine your module (with its associated dependencies) since it is already defined by app.js. Perhaps try attaching your controller to the existing module.
angular
.module('app')
.controller('JobCtrl', ...
Speaking of app.js, you should not need to inject any of your components/controllers/services since they will be programatically attached later.
angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls']);
I have the following code:
.service('loginModal', function($rootScope, $uibModal) {
function updateUserData(user, data) {
Object.keys(data).forEach(function(key) {
user.facebook[key] = data[key];
});
return user.$update();
}
return function() {
var instance = $uibModal.open({
templateUrl: 'tpls/modals/login.html',
controller: function($scope, $uibModalInstance, facebookService, UserService) {
function updateUserData(user, data) {
Object.keys(data).forEach(function(key) {
user.facebook[key] = data[key];
});
return user.$update();
}
$scope.login = function() {
facebookService.login().then(function(response) {
var authResponse = facebookService.getAuthResponse();
facebookService.api('/me').then(function(response) {
if (response && !response.error) {
response.picture = 'http://graph.facebook.com/' + response.id + '/picture?type=large';
UserService.query({
'facebook.id': response.id,
'facebook.token': authResponse.accessToken
}).$promise.then(function(results) {
response.token = {
value: authResponse.accessToken,
expiresIn: authResponse.expiresIn
};
if (results.length > 0)
updateUserData(results[0], response) //THIS DOES NOT FULFILL OR REJECT
.then($uibModalInstance.close, $uibModalInstance.dismiss);
else
UserService.save({
facebook: response,
local: {
username: response.email || response.id,
password: response.token.value
}
}).$promise
.then($uibModalInstance.close, $uibModalInstance.dismiss);
}, $uibModalInstance.dismiss);
} else {
$uibModalInstance.dismiss(response.error || response);
}
}, $uibModalInstance.dismiss);
}, $uibModalInstance.dismiss);
};
}
instance.opened.then(function() {
$rootScope.openModals.push(instance);
});
function removeInstanceFromModalList() {
$rootScope.openModals.splice($rootScope.openModals.indexOf(instance), 1);
}
instance.result.then(removeInstanceFromModalList, removeInstanceFromModalList);
return instance.result;
}
Basically I'm calling loginModal().then(function(user){...},function(e){...}); from wherever I want.
The part which does not work however is right after I query UserService
if (results.length > 0)
updateUserData(results[0], response) //THIS DOES NOT FULFILL OR REJECT
.then($uibModalInstance.close, $uibModalInstance.dismiss);
I've also tried debugging like this:
updateUserData(results[0], response)
.then(function(usr) {
$uibModalInstance.close(usr); //debugger reaches this statement,
//nothing happens
}, function(e) {
$uibModalInstance.dismiss(e);
});
What's wrong with my code? only backdrop clicks seem to close the dialog.
You can use the promise returned by $uibModal.open() which has the close() method attached.
You could store it in the controller $scope:
$scope.modal_instance = $uibModal.open({ ...
and then use:
$scope.modal_instance.close();
instead of $uibModalInstance.close.
Dangit - had a version issue.
Apperantly the version of angular-ui I was using was incompatible with angular#1.4.7 so I had to upgrade to 1.4.8.
I'm using AngularJs with Angular Routes and Phonegap to make my mobile app. It's an ecommerce app so there's a typical category page with filters and sorting and product details page.
Now the issue is whenever I'm on the product details page and click on back it forgets the sorting/filtering/pagination and basically loads the category page afresh.
Also in general how do i stop from hitting the api again when back button is clicked.
Here's how my category controller looks like.
app.controller('categoryController', function ($http, $scope, $location, $rootScope, $routeParams, $anchorScroll) {
loaderShow();
$scope.filtered = {};
$scope.minp = 0;
$scope.maxp = 0;
$scope.pdts = {};
$http.get(domain + "/get-category-products/" + $routeParams.url_key + (window.localStorage.getItem('id') != null ? "?userId=" + window.localStorage.getItem('id') : ""), {
cache: true
}).success(function (data, status, headers, config) {
$scope.products = data;
$scope.pdts = data.data
$scope.filters = data.filters;
$scope.$digest;
loaderHide();
});
$scope.load = function (event, url) {
angular.element(event.target).children("i").addClass("fa fa-spinner fa-pulse");
$http.get(url, {
params: {
'filters': $scope.filtered,
'minp': $scope.minp,
'maxp': $scope.maxp,
'slug': $routeParams.url_key,
'sort': jQuery("select.orderby").val(),
'userId': (window.localStorage.getItem('id') != null ? window.localStorage.getItem('id') : "")
},
cache: true
}).success(function (data, status, headers, config) {
$scope.products = data;
if (data.data.length > 0) {
jQuery.each(data.data, function (k, v) {
$scope.pdts.push(v);
});
angular.element(event.target).children("i").removeClass("fa fa-spinner fa-pulse");
} else {
angular.element(event.target).removeAttr("ng-click");
angular.element(event.target).text("No More Products");
}
$scope.$digest;
loaderHide();
});
};
$scope.filterProds = function (option, parent) {
if (option) {
if (!(parent in $scope.filtered))
$scope.filtered[parent] = [];
var idx = $scope.filtered[parent].indexOf(option);
if (idx > -1)
$scope.filtered[parent].splice(idx, 1);
else
$scope.filtered[parent].push(option);
if ($scope.filtered[parent].length <= 0)
delete $scope.filtered[parent];
}
};
$scope.applyFilters = function () {
$scope.minp = jQuery("#min_price").val();
$scope.maxp = jQuery("#max_price").val();
$http.get(domain + "/get-filtered-products", {
params: {
'filters': $scope.filtered,
'minp': $scope.minp,
'maxp': $scope.maxp,
'slug': $routeParams.url_key,
'sort': jQuery("select.orderby").val(),
'userId': (window.localStorage.getItem('id') != null ? window.localStorage.getItem('id') : "")
}
}).success(function (response) {
$scope.products = response;
$scope.pdts = response.data
$scope.$digest;
jQuery(".big-notification.yellow-notification").slideUp();
});
}
$scope.sizeOf = function (obj) {
return Object.keys(obj).length;
};
$scope.showFilters = function () {
jQuery(".big-notification.yellow-notification").toggle("slideDown");
}
$scope.showOptions = function (e) {
jQuery("#" + e).toggle();
}
$scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
siteMainFn();
});
});
Any help would be appreciated. Thanks
I am working on like and unlike section of an image. When a user likes an image, it pushes the userID to an array in mongodb. When a user unlikes an image, it removes the userID from the array. I am trying to do it using $addToSet and $pull.
Question: How can I do it in a single block instead of writing two separate bolcks for these two? Currently I am using a variable opr but it is not working. How can I make it work?
if(likeAction == "like"){
var opr = '$addToSet'
}
else if(likeAction == "unlike"){
var opr = '$pull'
}
Like.update(
{ imageID: imageID },
{ opr : { userIDs: userID } },
function(err){
if(!err){
Like.findOne({imageID : imageID}, function(err,like){
image.likeCount = like.userIDs.length
image.save(function(err){
if(!err){
return res.send({
status: {
error: 0,
message: "Successful"
}
})
}
})
})
}
}
);
I think this should work to combine both queries and solve the opr issue:
var update = {};
if (likeAction === 'like'){
update.$addToSet = { userIDs: userID };
update.$inc = { likeCount : 1 };
} else if (likeAction === 'unlike'){
update.$pull = { userIDs: userID };
update.$inc = { likeCount : -1 };
}
Like.update({ imageID: imageID }, update, ...);
You can do something like that :
var opr, updateCommande = {};
if(likeAction == "like"){
opr = '$addToSet'
}
else if(likeAction == "unlike"){
opr = '$pull'
}
updateCommande[opr]= { userIDs: userID }
Like.update(
{ imageID: imageID },
updateCommande,
function(err){
if(!err){
Like.findOne({imageID : imageID}, function(err,like){
image.likeCount = like.userIDs.length
image.save(function(err){
if(!err){
return res.send({
status: {
error: 0,
message: "Successful"
}
})
}
})
})
}
}
);