AngularJs Routes + Back Button - javascript

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

Related

AngularJS delete request button

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)});
};

How To Run Controller Functionality Again Using Different Parameters From View ng-model

I have a controller that works fine on initial load. It calls user [0] data and everything processes fine. When I change dropdown, I want to call the same function, but I cannot get the entire controller to reload. It starts from the function call and leaves undefined in places where it pulls correct information (linkToken, etc) on initial load. Is there a way I can get it to reload all data from the controller instead of just from the function?
After calling the testchange() from the view to pass in the new data, I get :
TypeError: Cannot read property 'locations' of undefined
at h.$scope.updateLocations (refillController.js:261)
at refillController.js:73
But, when I call the original getRefills() that is ran on the initial page load I get the same error. How can I define these so the load after the onchange(0)?
angular.module('FinalApp.Controllers').controller('refillController', function ($rootScope, $scope, $location, $modal, userService, dependentsService, accountService, sharedCollections, configurationService, refillsService) {
$scope.user = userService.GetUserInformation();
$scope.userInfoArr = [];
//$scope.tests.push({'Name':$scope.user.FirstName, 'LinkToken':$scope.user.LinkToken});
$scope.userInfoArr = $scope.user.Dependants.map(function(item){return {'Name':item.FirstName, 'LinkToken':item.LinkToken}});
$scope.userInfoArr.splice(0, 0, {'Name': $scope.user.FirstName, 'LinkToken': $scope.user.LinkToken});
console.log($scope.userInfoArr);
$scope.finUserInfoArr = $scope.userInfoArr[0].LinkToken;
$scope.billingInfo = null;
$rootScope.showNavbar = true;
$scope.selectedMethod = null;
$scope.location = null;
$scope.payment = null;
$scope.refills = [];
$scope.deliverTypes = [];
$scope.locations = [];
$scope.payments = [];
$scope.allSelected = false;
$scope.loadingBillingInfo = false;
$scope.isMailOrder = false;
//Detect Mobile Switch Refill List To Grid
if(window.innerWidth <= 800) {
$scope.view = "Grid";
} else {
$scope.view = "List";
}
$scope.changeViewToList = function () {
$scope.view = "List";
};
$scope.changeViewToGrid = function () {
$scope.view = "Grid";
};
$scope.testchange = function(selectedTest) {
$scope.getRefills(selectedTest);
console.log(selectedTest);
};
$scope.getRefills = function (linkToken) {
$scope.allSelected = false;
$scope.loading = true;
refillsService.GetRefills(
linkToken,
$scope.selectedMethod,
$scope.location,
$scope.payment
).then(function (data) {
$scope.refills = [];
_.each(data.Prescriptions, function (item) {
fillRefills(item);
});
fillDeliverTypes(data.DeliveryTypes);
if (!$scope.selectedMethod)
$scope.selectedMethod = data.DeliveryTypeId;
if (!$scope.location)
$scope.location = data.PickupLocationId;
if (!$scope.payment)
$scope.payment = data.PaymentTypeId;
$scope.loading = false;
$scope.updateLocations();
})["catch"](function (error) {
console.log(error);
$scope.loading = false;
alertify.alert(configurationService.ErrorMessage("getting your refills", error.Message));
});
};
var fillRefills = function (item) {
//TODO-CallDoc temp fix
if (item.RefillClass == "CALL_DOCTOR") {
item.NextRefillDate = '1900-01-01T00:00:00'
}
var parsedDate = checkDate(moment(item.NextRefillDate).format('L'));
var lastrefill = checkDate(moment(item.LastDispenseDate).format('L'));
var expireDate = checkDate(moment(item.ExpirationDate).format('L'));
var status = (item.RefillStatus.indexOf("After") == -1) ? item.RefillStatus : "Refill " + item.RefillStatus;
$scope.refills.push({
selected: false,
rx: item.ScriptNo,
name: item.DrugName,
dose: item.UnitsPerDose,
dir: item.Instructions,
nextfill: parsedDate,
lastfill: lastrefill,
refillsLeft: item.NumRefillsLeft,
status: status,
msg: item.RefillMessage,
canSelect: item.IsRefillable,
refillClass: item.RefillClass,
lastDispenseQty: item.LastDispenseQty,
DaysSupply: item.DaysSupply,
expireDate: expireDate,
copayAmt: item.CopayAmt,
drFirstName: item.DoctorFirstName,
drLastName: item.DoctorLastName,
writtenQty: item.WrittenQty
});
};
var checkDate = function (date) {
if (date == "01/01/1900") return "N/A";
if (date == "Invalid Date") return "";
return date;
};
var fillDeliverTypes = function (deliverTypes) {
$scope.deliverTypes = [];
_.each(deliverTypes, function (item) {
$scope.deliverTypes.push({
id: item.DeliveryTypeId,
name: item.DeliveryTypeName,
locations: item.PickupLocations,
payments: item.PaymentTypes
});
});
};
var getBillingInfo = function () {
$scope.loadingBillingInfo = true;
accountService.GetCreditCardInfo().then(function (data) {
$scope.billingInfo = data;
$scope.loadingBillingInfo = false;
})["catch"](function (error) {
$scope.loadingBillingInfo = false;
alertify.alert(configurationService.ErrorMessage("getting account information", error.Message));
});
};
var getAccountInfo = function () {
accountService.GetAccountInfo().then(function (data) {
if (data.StatusCode == "SUCCESS") {
$scope.user = data;
userService.SaveUserInformation(data);
if ($scope.user.IsLinked) {
$rootScope.enableMyRefills = true;
$rootScope.enableMyReports = true;
window.location.hash = "#/refills";
} else {
$rootScope.enableMyRefills = false;
$rootScope.enableMyReports = true;
}
} else {
alertify.alert(configurationService.ErrorMessage("getting account information", data.StatusMessage));
}
})["catch"](function (error) {
alertify.alert(configurationService.ErrorMessage("getting account information", error.Message));
});
};
var openModal = function (viewUrl, controllerUrl, size, payload) {
var modalInstance = $modal.open({
templateUrl: viewUrl,
controller: controllerUrl,
size: size,
resolve: {
data: function () {
return payload;
}
}
});
return modalInstance;
};
$scope.toggleRxSelection = function(rx) {
if (rx.canSelect) {
rx.selected = !rx.selected;
$scope.evaluateAllSelected();
}
};
$scope.selectAll = function (data) {
// $scope.allSelected = allSelected;
_.each($scope.refills, function (x) {
if (x.canSelect) x.selected = data;
});
};
$scope.evaluateAllSelected = function () {
var count = _.countBy(_.where($scope.refills, {canSelect:true}), function(refill) {
return refill.selected ? 'selected' : 'not';
});
$scope.allSelected = (count.not === undefined);
};
$scope.openEditCreditCardInfo = function () {
var payload = ($scope.billingInfo != null && $scope.billingInfo != undefined)
&& $scope.billingInfo.CardNumber != "" ? $scope.billingInfo : {};
if (payload != {}) {
payload.ExpMonth = {id: parseInt(payload.ExpMonth)};
payload.ExpYear = {id: parseInt(payload.ExpYear)};
}
openModal('app/views/editAccount/billingInformation.html', "billingInformationController", "xlg", payload).result.then(function () {
getAccountInfo();
getBillingInfo();
}, function () {
getBillingInfo();
});
};
$scope.openConfirmOrder = function () {
var refillsSelected = _.where($scope.refills, {selected: true});
var location = _.findWhere($scope.locations, {PickupLocationId: $scope.location});
var payment = _.findWhere($scope.payments, {PaymentTypeId: $scope.payment});
var deliver = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod});
if (refillsSelected.length == 0) {
alertify.error("You need to select at least one refill");
return;
}
if (deliver.id == 10001 && !$scope.user.IsCreditCardOnFile) {
alertify.error("Need credit card on file for mail order");
return;
}
sharedCollections.setRefills(refillsSelected);
sharedCollections.setLocation(location);
sharedCollections.setPayment(payment);
sharedCollections.setDeliver(deliver);
openModal('app/views/refills/confirmOrder.html', "confirmOrderController", "xlg").result.then(function () {
$scope.billingInfo = accountService.GetCreditCardInfo();
$scope.getRefills();
}, function () {
//$scope.billingInfo = accountService.GetCreditCardInfo();
//getRefills();
});
};
$scope.showRefill = function (rx) {
var data = {rx: rx, refills: $scope.refills};
openModal('app/views/refills/showRefills.html', "refillsCarrousel", "xlg", data).result.then(function () {
$scope.evaluateAllSelected();
}, function () {
$scope.evaluateAllSelected();
});
};
$scope.updateLocations = function () {
$scope.locations = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod}).locations;
$scope.payments = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod}).payments;
setLocationAndPayment();
};
var setLocationAndPayment = function () {
if ($scope.locations.length == 1) {
$scope.location = $scope.locations[0].PickupLocationId;
}
if ($scope.payments.length == 1) {
$scope.payment = $scope.payments[0].PaymentTypeId;
}
//check for mail order
($scope.selectedMethod == 10001 && !$scope.payment) ? $scope.isMailOrder = true : $scope.isMailOrder = false;
};
$scope.getRefills($scope.finUserInfoArr);
getBillingInfo();
});
Check if your refillsService returns correct data, it could be that $scope.refills remains empty array.

angularjs default select always changes

with angularjs select tab and ng-options,I cannot get the right default selecedValue after I selected one .
html
<select ng-model="selectedStyle" ng-options="style as style.name for style in styles"></select>
javascript
$scope.$on('openStyleList', function (event, page) {
styleListService.Get().
then(function (data) {
var tempArray = new Array();
if(page.pageType == 'Jacket')
{
tempArray.push(_.first(data))
$scope.styles = tempArray;
alert($scope.styles[0].name)//here i get the first one
$scope.selectedStyle = $scope.styles[0];//but here the $scope.selectedStyle is not always the first one! It's always the one that I selected before.I cannot set it to the default one($scope.styles[0])
}
else if (page.pageType == 'Body') {
if (_.rest(data).length == 1) {
tempArray.push(_.rest(data))
$scope.styles = tempArray;
}
else {
$scope.styles = _.rest(data);
}
alert($scope.styles[0].name)//aslo here
$scope.selectedStyle = $scope.styles[0];//aslo here
}
});
})
the styleListService code:
angular.module('editorApp')
.service('styleListService', ['$http', '$log', '$q', '$timeout', '$window', 'baseService', 'settings',
function styleListService($http, $log, $q, $timeout, $window, baseService, settings) {
var StyleListServiceFactory = {};
var _get = function () {
return baseService.get('styles/');
}
StyleListServiceFactory.Get = _get
return StyleListServiceFactory;
}]);
the part of baseService code :
var _get = function (apiPath, responsetype) {
var deferred = $q.defer();
if (responsetype == undefined)
{
responsetype = "";
}
$http.defaults.cache = false;
$http.get(settings.baseUrl + apiPath,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
responseType: responsetype
}).success(function (response) {
deferred.resolve(response);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
baseServiceBaseFactory.get = _get;
1) Select your default value as model
you can do this like
<select tabindex="2" class="dropdown-control " id="drpSystemDeliveryCos" ng-model="selecedValue ">
<option ng-repeat="style in styles" value="{{style .ID}}">{{style .name}}</option>
</select>
OR
<select tabindex="6" class="form-control" id="drpOrderType1" ng-options="style.ID as style.name for style in styles " ng-model="selecedValue" ></select>

how can i get the element that triggered an event that if the event is defined in a directive

here are lines from a built in directive(blueimp)
.controller('FileUploadController', [
'$scope', '$element', '$attrs', '$window', 'fileUpload',
function ($scope, $element, $attrs, $window, fileUpload) {
alert('incontroller');
var uploadMethods = {
progress: function () {
return $element.fileupload('progress');
},
active: function () {
return $element.fileupload('active');
},
option: function (option, data) {
return $element.fileupload('option', option, data);
},
add: function (data) {
return $element.fileupload('add', data);
},
send: function (data) {
return $element.fileupload('send', data);
},
process: function (data) {
return $element.fileupload('process', data);
},
processing: function (data) {
return $element.fileupload('processing', data);
}
};
$scope.disabled = !$window.jQuery.support.fileInput;
$scope.queue = $scope.queue || [];
$scope.clear = function (files) {
var queue = this.queue,
i = queue.length,
file = files,
length = 1;
if (angular.isArray(files)) {
file = files[0];
length = files.length;
}
while (i) {
i -= 1;
if (queue[i] === file) {
return queue.splice(i, length);
}
}
};
$scope.replace = function (oldFiles, newFiles) {
var queue = this.queue,
file = oldFiles[0],
i,
j;
for (i = 0; i < queue.length; i += 1) {
if (queue[i] === file) {
for (j = 0; j < newFiles.length; j += 1) {
queue[i + j] = newFiles[j];
}
return;
}
}
};
$scope.applyOnQueue = function (method) {
var list = this.queue.slice(0),
i,
file;
for (i = 0; i < list.length; i += 1) {
file = list[i];
if (file[method]) {
file[method]();
}
}
};
$scope.submit = function () {
this.applyOnQueue('$submit');
};
$scope.cancel = function () {
this.applyOnQueue('$cancel');
};
// Add upload methods to the scope:
angular.extend($scope, uploadMethods);
// The fileupload widget will initialize with
// the options provided via "data-"-parameters,
// as well as those given via options object:
$element.fileupload(angular.extend(
{scope: function () {
return $scope;
}},
fileUpload.defaults
)).on('fileuploadadd', function (e, data) {
data.scope = $scope.option('scope');
}).on('fileuploadchange', function (e, data) {
data.scope = $scope.option('scope');
data.scope.extend({
mycustomfield:$element
//i added above line, is it illegal, or too ugly to get element,or needless,some other way?
});
}).on([
'fileuploadadd',
'fileuploadsubmit',
'fileuploadsend',
'fileuploaddone',
'fileuploadfail',
'fileuploadalways',
'fileuploadprogress',
'fileuploadprogressall',
'fileuploadstart',
'fileuploadstop',
'fileuploadchange',
'fileuploadpaste',
'fileuploaddrop',
'fileuploaddragover',
'fileuploadchunksend',
'fileuploadchunkdone',
'fileuploadchunkfail',
'fileuploadchunkalways',
'fileuploadprocessstart',
'fileuploadprocess',
'fileuploadprocessdone',
'fileuploadprocessfail',
'fileuploadprocessalways',
'fileuploadprocessstop'
].join(' '), function (e, data) {
if ($scope.$emit(e.type, data).defaultPrevented) {
e.preventDefault();
}
}).on('remove', function () {
// Remove upload methods from the scope,
// when the widget is removed:
var method;
for (method in uploadMethods) {
if (uploadMethods.hasOwnProperty(method)) {
delete $scope[method];
}
}
});
// Observe option changes:
$scope.$watch(
$attrs.fileUpload,
function (newOptions) {
if (newOptions) {
$element.fileupload('option', newOptions);
}
}
);
}
])
.directive('fileUpload', function () {
return {
controller: 'FileUploadController',
scope: true
};
})
i can see reaction on my template controller
$scope.$on('fileuploadchange',function(e,data){
//here i want to get element which is the source of event
//if you can look at above code piece, i think i can get the element by
//data.scope.mycustomfield
}
some nicer way?

Controller not firing in AngularJS

I'm having an odd issue in AngularJS where MainCtrl isn't fire at all. I go to localhost/ and it redirects to localhost/#/ but the page is blank. There are no errors/messages in console. I can confirm that /views/main.html is publicly accessible. I don't know why this isn't working. Am I missing anything?
angular.module('TurkApp', ['ngCookies']).config([
'$routeProvider',
function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
}).otherwise({ redirectTo: '/' });
}
]);
angular.module('TurkApp', []).controller('MainCtrl', [
'$scope',
'$http',
'$location',
'$cookies',
function ($scope, $http, $location, $cookies) {
$scope.questionIsLoading = true;
$scope.answerButtonsDisabled = true;
$scope.showHelp = false;
$scope.currentRetries = 0;
$scope.acceptedHit;
$scope.currentQuestionText = null;
$scope.currentQuestionID = null;
var AssignmentID, Interest;
var getInterest = function () {
return $cookies.interest;
};
var getAssignmentID = function () {
var qsRegex = new RegExp('(?:\\?|&)AssignmentID=(.*?)(?=&|$)', 'gi'), m, assignmentID = false;
while ((match = qsRegex.exec(document.location.search)) != null) {
assignmentID = match[1];
}
if (!assignmentID) {
assignmentID = $location.search()['AssignmentID'];
}
$scope.acceptedHit = assignmentID == 'ASSIGNMENT_ID_NOT_AVAILABLE' || !assignmentID ? false : true;
return assignmentID;
};
$scope.loadNextQuestion = function () {
$scope.questionIsLoading = $scope.answerButtonsDisabled = true;
$http.get('/workers/' + Interest + '/next-question').success(function (data, status) {
$scope.currentQuestionText = data.text;
$scope.currentQuestionID = data.id;
$scope.questionIsLoading = $scope.answerButtonsDisabled = false;
}).error(function () {
console.log('Answer send failed');
});
};
$scope.sendAnswer = function (answer) {
if (!$scope.questionIsLoading && !$scope.answerButtonsDisabled) {
$scope.questionIsLoading = $scope.answerButtonsDisabled = true;
$http.post('/workers/' + Interest + '/answer-question', {
question_id: $scope.currentQuestionID,
question_text: $scope.currentQuestionText,
answer: answer
}).success(function (data, status) {
$scope.loadNextQuestion();
}).error(function () {
console.log('Answer send failed');
});
}
};
$scope.toggleHelp = function () {
$scope.showHelp = $scope.showHelp ? false : true;
};
var init = function () {
AssignmentID = getAssignmentID();
Interest = getInterest();
$scope.loadNextQuestion();
};
init();
}
]);
You are creating the module 'TurkApp' twice, thereby losing the configuration registered with the first module:
angular.module('TurkApp', ['ngCookies'])
When you include the second parameter to the angular.module function, it creates the module. If you omit the second parameter, it assumes the modules exists and "extends" it.
Change:
angular.module('TurkApp', [])
to:
angular.module('TurkApp')
See the usage section here - http://docs.angularjs.org/api/angular.module

Categories