Create a child node in a nested firebase using angularJS - javascript

I am trying to create a child node for the "title" in the firebase. I am not able to give reference to the firebase and create a child called 'time' and store the time each time the user clicks the button.Here is the screenshot of my firebase.
Here is my code:
.controller('ListCtrl', function($scope, $firebaseAuth,$ionicListDelegate, $firebaseObject, $ionicPopup, $interval, $firebase) {
$scope.stopSpam = false;
$scope.list = function(){
var FB = new Firebase("https://my-project.firebaseio.com");
var fbAuth = $firebaseAuth(FB);
fbAuth = FB.getAuth();
if(fbAuth) {
var syncObject = $firebaseObject(FB.child("users/" + fbAuth.uid));
syncObject.$bindTo($scope, "data");
}
}
$scope.addItem = function() {
$ionicPopup.prompt({
title: 'Enter a task you want to add',
inputType: 'text'
})
.then(function(result) {
if(result !== "") {
if($scope.data.hasOwnProperty("todos") !== true) {
$scope.data.todos = [];
}
$scope.data.todos.push({title: result});
} else {
console.log("Action not completed");
}
});
}
$scope.doneItem = function(todo) {
$scope.todo = todo;
$scope.todo['stopSpam'] = true;
$interval(callAtInterval, 3000);
function callAtInterval(){
todo.stopSpam = false;
}
};
});

Related

Console Error in $element, while using $mdDialog of AngularJS Material

I'm trying to solve this error that shows in the console, it only occurs on the server, in my localhost the modal works correctly. Here's the error (click to open its link):
I have a view with the controller:
.when('/aseguradora', {
templateUrl: 'views/insuranceagentdashboard.html',
controller: 'InsuranceagentdashboardCtrl'
})
This is the controller:
angular.module('virtualApp').controller('InsuranceagentdashboardCtrl', ['$http', '$scope', 'pager', 'Dialogs', function($http, $scope, pager, Dialogs) {..
Inside the controller I have a function that executes the modal, (Dialogs is a service):
$scope.showCosignerFormDialog = function(insuranceRequest) {
Dialogs.cosignerFormdialog(insuranceRequest);
}
In HTML I have an md-button with an ng-click
<md-button class="md-color-green" ng-click="showCosignerFormDialog(insuranceRequest)">VER SOLICITUD</md-button>
This is the Dialog service that executes the modal:
dialogs.cosignerFormdialog = function(insuranceRequest) {
return $mdDialog.show({
templateUrl: 'views/cosignerformdialog.html',
autoWrap: false,
controller: 'IdentityVerificationWizardCtrl',
locals: {
listing: insuranceRequest
},
preserveScope: true,
escapeToClose: false,
fullscreen: true,
clickOutsideToClose: true
});
};
I do not know why this error can occur in the console being in the URL of the server, if I am in my localhost I do not get this error ...
THIS IS CONTROLLER identityverificationwizard.js:
angular.module('virtualApp').controller('IdentityVerificationWizardCtrl', ['$scope', 'upload', '$http', 'listing', '$routeParams', '$location', 'Dialogs', '$element', function($scope, upload, $http, listing, $routeParams, $location, Dialogs, $element) {
$scope.propertyListing = listing;
$scope.insuranceStudyContactInfo = {};
$scope.insuranceStudyJobInfo = {};
$scope.insuranceStudyFinancialInfo = {};
$scope.insuranceStudyAssets = {};
$scope.identityInfo = {
date : moment('01/01/2000', 'DD/MM/YYYY').toDate()
};
$scope.virtualSignatureInfo = {};
$scope.isCorporation = 'false';
$scope.insuranceStudyJobInfo.publicOfficer = false;
$scope.insuranceStudyJobInfo.managesPublicFunds = false;
$scope.insuranceStudyJobInfo.linkedToRenownedPeople = false;
$scope.insuranceStudyJobInfo.vatResponsible = false;
$scope.insuranceStudyJobInfo.greatContributor = false;
$scope.insuranceStudyFinancialInfo.doImport = false;
$scope.insuranceStudyFinancialInfo.doExport = false;
$scope.insuranceStudyFinancialInfo.doInvest = false;
$scope.insuranceStudyFinancialInfo.doCurrencyExchange = false;
$scope.insuranceStudyFinancialInfo.doPayServices = false;
$scope.insuranceStudyFinancialInfo.doPayLoans = false;
$scope.insuranceStudyFinancialInfo.doTransactions = false;
$scope.rentProcessId = $scope.propertyListing.rentProcessId;
$scope.cosignerKey = $location.search().cosignerKey;
if ($scope.rentProcessId || $scope.cosignerKey) {
$scope.readOnly = false;
} else {
$scope.readOnly = true;
}
$scope.setTabIndex = function(index) {
$scope.tabIndex = index;
}
$scope.fileChanged = function(kind, file) {
var reader = new FileReader();
reader.onload = function(e) {
if (kind == 'front') {
$scope.frontIdFile = file;
$scope.frontIdImage = e.target.result;
$scope.$apply();
} else {
$scope.backIdFile = file;
$scope.backIdImage = e.target.result;
$scope.$apply();
}
};
reader.readAsDataURL(file.files[0]);
$scope.$apply();
}
$scope.uploadForm = function() {
var params = {};
if ($scope.insuranceStudyContactInfo.city) {
$scope.insuranceStudyContactInfo.cityCode = $scope.insuranceStudyContactInfo.city.cityCode;
}
if ($scope.insuranceStudyJobInfo.city) {
$scope.insuranceStudyJobInfo.cityCode = $scope.insuranceStudyJobInfo.city.cityCode;
}
if ($scope.insuranceStudyAssets.hasProperties) {
if ($scope.insuranceStudyAssets.property1 && $scope.insuranceStudyAssets.property1.city) {
$scope.insuranceStudyAssets.property1.cityCode = $scope.insuranceStudyAssets.property1.city.cityCode || null;
} else {
delete $scope.insuranceStudyAssets.property1;
}
if ($scope.insuranceStudyAssets.property2 && $scope.insuranceStudyAssets.property2.city) {
$scope.insuranceStudyAssets.property2.cityCode = $scope.insuranceStudyAssets.property2.city.cityCode || null;
} else {
delete $scope.insuranceStudyAssets.property2;
}
} else {
delete $scope.insuranceStudyAssets.property1;
delete $scope.insuranceStudyAssets.property2;
}
if ($scope.propertyListing.rentProcessId) {
params.rentProcessId = $scope.propertyListing.rentProcessId;
}
if ($location.search().cosignerKey) {
params.cosignerKey = $location.search().cosignerKey;
}
if ($scope.identityInfo.date) {
$scope.identityInfo.birthDate = formatedDate($scope.identityInfo.date, 'DD/MM/YYYY');
}
$scope.insuranceStudyFinancialInfo.doImport = $scope.insuranceStudyFinancialInfo.doImport || false;
$scope.insuranceStudyFinancialInfo.doExport = $scope.insuranceStudyFinancialInfo.doExport || false;
$scope.insuranceStudyFinancialInfo.doInvest = $scope.insuranceStudyFinancialInfo.doInvest || false;
$scope.insuranceStudyFinancialInfo.doCurrencyExchange = $scope.insuranceStudyFinancialInfo.doCurrencyExchange || false;
$scope.insuranceStudyFinancialInfo.doPayServices = $scope.insuranceStudyFinancialInfo.doPayServices || false;
$scope.insuranceStudyFinancialInfo.doPayLoans = $scope.insuranceStudyFinancialInfo.doPayLoans || false;
$scope.insuranceStudyFinancialInfo.doTransactions = $scope.insuranceStudyFinancialInfo.doTransactions || false;
params.isCorporation = $scope.isCorporation;
params.contactInfo = JSON.stringify($scope.insuranceStudyContactInfo);
params.jobInfo = JSON.stringify($scope.insuranceStudyJobInfo);
params.financialInfo = JSON.stringify($scope.insuranceStudyFinancialInfo);
params.assets = JSON.stringify($scope.insuranceStudyAssets);
params.virtualSignatureInfo = JSON.stringify($scope.virtualSignatureInfo);
params.identityInfo = JSON.stringify($scope.identityInfo);
$scope.isReadOnly = function() {
if ($scope.readOnly) {
$http.get(root + "Insurance/s/getInsuranceRequest", {
params: {
insuranceRequestId: $scope.propertyListing.insuranceRequestId
}
}).then(function(res) {
$scope.code = res.data.code;
$scope.type = res.data.type;
$scope.datetime = res.data.datetime;
$scope.status = res.data.status;
$scope.listingCode = res.data.listingCode;
$scope.isCorporation = res.data.corporation + "";
$scope.identityInfo.documentTypeCode = res.data.identityInfo.documentTypeCode;
$scope.identityInfo.documentNumber = res.data.identityInfo.documentNumber;
$scope.identityInfo.names = res.data.identityInfo.names;
$scope.identityInfo.lastNames = res.data.identityInfo.lastNames;
$scope.identityInfo.date = res.data.identityInfo.birthDate;
$scope.insuranceStudyContactInfo = res.data.contactInfo;
$scope.insuranceStudyJobInfo = res.data.jobInfo;
$scope.insuranceStudyFinancialInfo = res.data.financialInfo;
if ($scope.insuranceStudyFinancialInfo.foreignAccountBank) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccount) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccountCurrency) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccountCountry) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.foreignAccountCity) {
$scope.insuranceStudyFinancialInfo.doForeignAccount = true;
}
if ($scope.insuranceStudyFinancialInfo.doImport) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doExport) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doInvest) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doCurrencyExchange) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doPayServices) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doPayLoans) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
if ($scope.insuranceStudyFinancialInfo.doTransactions) {
$scope.insuranceStudyFinancialInfo.doInternationalOperations = true;
}
$scope.insuranceStudyAssets = res.data.assets;
if ($scope.insuranceStudyAssets.property1 || $scope.insuranceStudyAssets.property2) {
$scope.insuranceStudyAssets.hasProperties = true;
}
if ($scope.insuranceStudyAssets.vehicle1 || $scope.insuranceStudyAssets.vehicle2) {
$scope.insuranceStudyAssets.hasCars = true;
}
$scope.availableActions = res.data.availableActions;
});
}
}
$scope.isReadOnly();
}]);
That error says your are using an unknown dependency in your controller.
Here, the error says that the "unknown dependency" is a provider called $element.
! There are 3 types of providers in angularjs: service, factory or provider
2 reasons why you can have this problem:
1) If you don't have any providers (service, factory or provider) called $element in your project you shouldn't have a dependency for it.
In IdentityVerificationWizardCtrl
Instead of:
.controller('IdentityVerificationWizardCtrl', ['$scope', 'upload', '$http', 'listing', '$routeParams', '$location', 'Dialogs', '$element', function($scope, upload, $http, listing, $routeParams, $location, Dialogs, $element)
Write:
.controller('IdentityVerificationWizardCtrl', ['$scope', 'upload', '$http', 'listing', '$routeParams', '$location', 'Dialogs', function($scope, upload, $http, listing, $routeParams, $location, Dialog)
2) if you have a provider called $element , maybe you didn't call it into your index.html
PS: In angularjs, $element is a parametter used into the link function and refer to the DOM element. So IMO opinion your error is because of reason 1

How do I pre-cache url content in ionic 1/angular 1?

I am pretty new to ionic and working on an app where you load a bunch of categories ,followed by a list of items in the category and when you click on the item in the category a documenturl loads containing the content which is basically an image. Currently, everything loads fine, but I would like to preload the content the moment my category is visible, so even if I go offline I should be able to click on any of the items within the category list and load the respective document. I looked online but I couldn't find anything except localstorage which caches data after you have visited it and not before. Is there a way I can pre-load or pre-cache content ?
Here's my code for controllers:
angular.module('starter.controllers', ["utility.services"])
.directive("bindCompiledHtml", ["$compile", "zoomPerOrientation", function($compile, zoomPerOrientation) {
return {
template: '<div></div>',
scope: {
rawHtml: '=bindCompiledHtml'
},
link: function(scope, elem, attrs) {
scope.$watch('rawHtml', function(value) {
if (!value) return;
var newElem = $compile(value)(scope.$parent);
elem.contents().remove();
zoomPerOrientation.zoomTo('docScroll');
elem.append(newElem);
elem.bind("click", function(e) {
e.stopPropagation();
e.preventDefault();
if (e.target.tagName === 'A') {
window.open(encodeURI(e.target.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
return false;
} else if (e.target.parentNode.tagName === 'A') {
window.open(encodeURI(e.target.parentNode.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
return false;
}
});
});
}
};
}])
.directive('setHeight', function($window) {
return {
link: function(scope, element, attrs) {
element.css('height', $window.innerHeight + 30);
}
}
})
.controller("MenuCtrl", ["$scope", "MenuService", "$stateParams", "$state", "ConfigUrls", function($scope, MenuService, $stateParams, $state, ConfigUrls) {
// debugger;
console.log("MenuCtrl");
$scope.menuData = [];
$scope.noMenuDataMsg = "Loading....";
$scope.LoadMenu = function(forceLoad) {
console.log("MenuCtrl - LoadMenu");
// console.log(MenuService.getClinicalAreas(forceLoad));
MenuService.getClinicalAreas(forceLoad).then(function(data) {
$scope.menuData = data;
}, function(err) {
console.log(err);
if (err.error === "timeout") {
$scope.noMenuDataMsg = "Error: Unable to retrieve data due to network error! Please try again when you are in network."
} else {
$scope.noMenuDataMsg = "Error retrieving data! Please contact system administrator."
}
$scope.menuData = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.deviceModel = window.localStorage.getItem("deviceModel");
// console.log(MenuService);
// console.log($scope.menuData);
$scope.title = $stateParams.topTitle;
var metaTag = $stateParams.metaTag;
//console.log(ConfigUrls[metaTag+"Published"]);
if (metaTag !== "") {
window.localStorage.setItem('publishedUrl', ConfigUrls[metaTag + "Published"]);
window.localStorage.setItem('docUrl', ConfigUrls[metaTag + "DocUrl"]);
window.localStorage.setItem('cacheKeyPrefix', metaTag);
$scope.LoadMenu(false);
} else {
$scope.noMenuDataMsg = "Under Construction!";
}
//console.log("metaTag",metaTag);
//if ($stateParams.topTitle === "Transplant") {
// $scope.LoadMenu(false);
//}
//else {
// $scope.noMenuDataMsg = "Under Construction!";
//}
$scope.showHomeItem = function(clinicalArea) {
console.log("MenuCtrl - showHomeItem");
$state.go('contr.home', {
cA: clinicalArea
});
}
$scope.goHome = function() {
console.log("MenuCtrl - goHome");
$state.go('contr.topmenu');
}
}])
.controller("HomeCtrl", ["$scope", "HomeService", "$stateParams", "$state", function($scope, HomeService, $stateParams, $state) {
console.log("HomeCtrl");
$scope.organs = [];
$scope.title = $stateParams.cA;
$scope.LoadHome = function(forceLoad) {
console.log("HomeCtrl - LoadHome");
HomeService.getOrgans($stateParams.cA, forceLoad).then(function(data) {
$scope.organs = data;
}, function(err) {
$scope.organs = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.showLevel2Item = function(title, clinicalArea) {
console.log("HomeCtrl - showLevel2Item");
$state.go('contr.level2', {
title: title,
cA: clinicalArea
});
//:title/:cA
}
$scope.goHome = function() {
console.log("HomeCtrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadHome(false);
}])
.controller('Level2Ctrl', ["$scope", "OrganService", "$stateParams", "$state", function($scope, OrganService, $stateParams, $state) {
$scope.title = "Level2 ";
console.log("Level2Ctrl");
$scope.parentOrgan = {};
$scope.viewTitle = $stateParams.title;
OrganService.getSingleOrganDetail($stateParams.cA, $stateParams.title).then(function(data) {
$scope.parentOrgan = data[0];
$scope.parentOrgan.clinicalAreaDisp = "Transplant";
}, function(err) {
$scope.parentOrgan = {};
});
console.log($scope.parentOrgan);
$scope.subGroup = [];
$scope.LoadSubGroups = function(forceLoad) {
console.log("Level2Ctrl - LoadSubGroups");
OrganService.getSubGroups($stateParams.title, $stateParams.cA, forceLoad).then(function(data) {
$scope.subGroup = data;
console.log("$scope.subGroup", $scope.subGroup);
}, function(err) {
$scope.subGroup = [];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
}
//$scope.deviceModel = window.localStorage.getItem("deviceModel");
//$scope.devicePlatform = window.localStorage.getItem("devicePlatform");
$scope.toggleGroup = function(group) {
group.show = !group.show;
};
$scope.isGroupShown = function(group) {
return group.show;
};
$scope.showDocumentDtl = function(id, docTitle, sgName, mnGroup, area) {
console.log("Level2Ctrl - showDocumentDtl");
$state.go('contr.doc-dtl', {
id: id,
docTitle: docTitle,
sgName: sgName,
mnGroup: mnGroup,
area: area
});
//:title/:cA
}
$scope.goHome = function() {
console.log("Level2Ctrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadSubGroups();
}])
.controller('DocumentCtrl', ["$scope", "DocmentService", "zoomPerOrientation", "$stateParams", "$ionicScrollDelegate", "$state", function($scope, DocmentService, zoomPerOrientation, $stateParams, $ionicScrollDelegate, $state) {
$scope.viewData = {};
$scope.snippet = "<p style='margin-top:40%;margin-left:40%;font-weight:bold;font-size:1.6em;' class='item item-stable'>Loading...</p>";
$scope.statusMessage = "";
$scope.title = $stateParams.mnGroup;
console.log("DocumentCtrl");
console.log("$stateParams", $stateParams);
//, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area
// console.log("Inside docuemtn controller");
$scope.LoadDocument = function(forceLoad) {
console.log("DocumentCtrl - LoadDocument");
DocmentService.getRowDocument($stateParams.id, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area, forceLoad).then(
function(data) {
// console.log("successfull", data);
$scope.viewData = data;
$scope.snippet = $scope.viewData.document;
},
function(reason) {
// console.log("Error Occured", reason);
$scope.viewData = {
"docTitle": "Error Occured!"
};
if (reason.error === "timeout") {
$scope.snippet = "<div style='margin-top:40%;margin-left:15%;font-weight:bold;font-size:1.6em;width:600px !important;padding:16px !important;line-height:120%;' class='item item-stable item-text-wrap item-complex'>Error: Unable to the load the document at this time. Please make sure you are in the network or you have already fetched the document while you were in the network!</div>";
}
// $scope.statusMessage = err;
}).finally(function() {
console.log("finally", data);
$scope.$broadcast('scroll.refreshComplete');
});
}
//below code would be refactored in near future.
//It is not a good practice adding window event listener in the controller
window.addEventListener('orientationchange', function() {
try {
if ($ionicScrollDelegate.$getByHandle('docScroll')._instances.length > 2) {
zoomPerOrientation.zoomTo('docScroll');
}
} catch (exception) {
console.log(exception);
}
});
$scope.goHome = function() {
console.log("DocumentCtrl - goHome");
$state.go('contr.topmenu');
}
$scope.LoadDocument(true);
}])
.controller('TopMenuCtrl', ["$scope", "TopMenuService", "$state", "$ionicHistory",
function($scope, TopMenuService, $state, $ionicHistory) {
$ionicHistory.clearHistory();
$scope.title = "Rules";
$scope.menuItems = [];
$scope.menuItemsLandscape = [];
$scope.flatMenuItems = [];
$scope.tileView = true;
$scope.listView = false;
$scope.portraitMode = true;
console.log("TopMenuCtrl");
TopMenuService.getMenuItems().then(function(data) {
$scope.menuItems = data.colData;
$scope.flatMenuItems = data.flatData;
$scope.menuItemsLandscape = data.threeColData;
console.log($scope.menuItems);
},
function() {
$scope.menuItems = [];
});
$scope.showMenuItem = function(title, metaTag) {
console.log("TopMenuCtrl - showMenuItem");
//$state.go('tab.menu', { topTitle: title });
$state.go('contr.menu', {
topTitle: title,
metaTag: metaTag
});
}
$scope.itemChanged = function() {
console.log("TopMenuCtrl - itemChanged");
console.log($scope.tileView);
if ($scope.tileView) {
$scope.listView = true;
$scope.tileView = false;
} else {
$scope.listView = false;
$scope.tileView = true;
}
}
// console.log(window.orientation);
function onChangeOrientation() {
console.log("TopMenuCtrl - onChangeOrientation");
try {
//landscape mode
// console.log("Orientation Changed");
if (window.orientation === 90 || window.orientation == -90) {
$scope.portraitMode = false;
}
//portrait
else {
$scope.portraitMode = true;
}
} catch (exception) {
console.log(exception);
}
}
onChangeOrientation();
window.addEventListener('orientationchange', function() {
try {
//landscape mode
// console.log("Orientation Changed");
if (window.orientation === 90 || window.orientation == -90) {
$scope.$apply(function() {
$scope.portraitMode = false;
});
}
//portrait
else {
$scope.$apply(function() {
$scope.portraitMode = true;
});
}
} catch (exception) {
console.log(exception);
}
});
}
])
.controller('LoginController', ["$scope", "$location", "$ionicHistory", '$timeout', '$ionicLoading', '$state',
function($scope, $location, $ionicHistory, $timeout, $ionicLoading, $state) {
$scope.username = "Guest";
$scope.password = "Abcd123";
// $ionicNavBarDelegate.showBar(false);
$scope.login = function(password) {
console.log("LoginController - login");
if (password) {
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
template: '<p class="item-icon-left bar-header"><ion-spinner icon="lines"/></p>',
maxWidth: 200,
showDelay: 0
});
window.localStorage.setItem("Pswd", password);
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$timeout(function() {
$ionicLoading.hide();
//$location.path("/tab/topmenu");
$state.go('contr.topmenu');
}, 1000);
}
}
}
])
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
Please let me know if you need any other info.Also, currently I do support local cache to cache categories locally, but not pre-cached. Is there a way to retrieve these documents beforehand? Please check my loaddocuments section which deals with loading document url's once you click on the specific item.
Please refer this I've already explained everything with programming approach.
StackOverflow Solution Link
You can use this explained approach, and adding for others who are looking for answer to this question.

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 - ng-bind not updating

I have a controller which has a function to get some alerts from an API and update a count on the front-end of my site which is bound to the alert.
Unfortunately the ng-bind attribute I'm using doesn't seem to be updating the count live, even though a simple console.log() is telling me that the actual alert count is being updated in the controller.
Front-end
<div class="modeSelector modeSelector_oneUp" data-ng-controller="MyLivestockController as vm">
<a class="modeSelector-mode" data-ui-sref="my-livestock">
<div class="modeSelector-type">Alerts</div>
<img class="modeSelector-icon" src="/inc/img/_icons/envelope-black.svg" onerror="this.src=envelope-black.png" />
<span data-ng-bind="vm.alertCount"></span>
</a>
</div>
Controller
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
angular
.module('abp')
.controller('MyLivestockController', MyLivestockController);
})();
Service
(function() {
'use strict';
function userService($q, $sessionStorage, $localStorage, $filter, user) {
var service = this;
service.getAlerts = function(id) {
var deferred = $q.defer();
user.alerts({ userID: id }, function(response) {
if (response.hasOwnProperty('data')) {
// Convert dates to valid Date
angular.forEach(response.data, function(alert) {
/* jshint camelcase: false */
if (alert.created_at) {
alert.created_at = $filter('abpDate')(alert.created_at);
/* jshint camelcase: true */
}
});
deferred.resolve(response.data);
}
else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
angular
.module('abp')
.service('userService', userService);
})();
As you can see, I've got my getAlerts() function being called every time an alert is deleted, using the deleteAlert() function, but the <span data-ng-bind="vm.alertCount"></span> on the front-end only updates after refreshing the page, where I'd like it to update live.
Your bind is not updating because you change the value of alertCount outside of digest cycle of your angular app. When you refresh your app, the digest runs and thus your value gets updated. Wrap the update of the variable in $scope.apply() like so:
$scope.$apply(function(){
vm.alertCount = alertData.length;
});
This will force digest and update the value live.
If you have more values that are updated outside of digest (any callback, promise etc) you can force digest cycle by calling:
$scope.$apply();
Hope it helps.
EDIT -----
Given your update with full code, I see that you are not injecting scope anywhere in your controller, the controllers I write usually start like that:
(function () {
var app = angular.module('mainModule');
app.controller('myController', ['$scope', '$myService', function ($scope, $myService) {
//logic
}]);
}());
EDIT -----
Here is a quick go I had on your code:
(function() {
'use strict';
var app = angular.module('abp');
app.controller('MyLivestockController', ['$scope', 'userService', function($scope, userService) {
var vm = {};
$scope.vm = vm;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
//important, this is promise so we have to apply the scope to update view
$scope.$apply();
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}]);
})();
The general idea is:
you create an app (angular.module)
you create a controller in this app, with $scope injected
any values you want to be updated on your view, you add to $scope
if you have any $scope updates in a callback, event or promise, you wrap them in (or follow with) $scope.$apply call
I think this should work for you :)
I have attempted to reproduce your code below with a mock userService, and some slight modifications to the html view so we can more clearly see the alerts and delete them. I have not modified your Controller.
This appears to work, yes?
Which leads me to believe there may be some issue with the implementation of your userService. If you are able to post the relevant code, I can update this answer with a clarified solution.
UPDATE: As you've updated your question with the userService code, I've updated the below to more closely match. I still have a mock service standing in place of the user dependency of the userService. Additionally I made a couple of small edits to the Controller class so that while promises are still resolving we can see 'Updating...' in place of the alerts count.
This all still appears to work, unless I'm misunderstanding - will think on it more and update this 'answer' when I can think of where else to investigate for the source of the issue, see if we can at least reproduce it!
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
return userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id).then(function() {
vm.alertsNotification.isLoading = false; //put here, loading isn't really finished until after .getAlerts() is done
vm.alertsNotification.hasError = false;
});
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
vm.alertsNotification.isLoading = true;
return userService.getAlerts(id).then(function(alertData) { //return the promise so we can chain .then in .deleteAlert()
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
function userMock($q, $timeout, $log) {
var _alerts = {
data: [{
id: 1,
message: "He doesn't sleep, he waits..."
}, {
id: 2,
message: "He doesn't mow his lawn, he stands outside and dares it to grow."
}, {
id: 3,
message: "Some magicians can walk on water. He can swim through land."
}]
},
_currentUser = {
id: 'Q2h1Y2sgTm9ycmlz'
};
return {
getCurrentUser: function getCurrentUser() {
$log.log("getCurrentUser");
//return $q.when(_currentUser);
return $timeout(function() { //use $timeout to simulate some REST API latency...
return _currentUser;
}, 500);
},
getAlerts: function getAlerts(id) {
$log.log("getAlerts: " + id); //not doing anything with the id in this mock...
$log.log(_alerts.data);
//return $q.when(_alerts);
return $timeout(function() {
return _alerts;
}, 500);
},
deleteAlert: function deleteAlert(userId, id) {
$log.log("deleteAlert: " + userId + " :: " + id);
//return $q.when(_alerts);
return $timeout(function() {
for (var i = 0; i < _alerts.data.length; i++) {
if (_alerts.data[i].id === id) {
_alerts.data.splice(i, 1);
$log.log("alert found and deleted");
break;
}
}
$log.log(_alerts.data);
return _alerts;
}, 500);
}
};
}
function userService($q, $timeout, $log, userMock) {
var service = this;
service.getCurrentUser = userMock.getCurrentUser;
service.getAlerts = function(id) {
var deferred = $q.defer();
userMock.getAlerts(id).then(function(response) {
if (response.hasOwnProperty('data')) {
// Convert 'he' to 'Chuck Norris'
angular.forEach(response.data, function(alert) {
if (alert.message) {
alert.message = alert.message.replace(/he/gi, "Chuck Norris");
}
});
deferred.resolve(response.data);
} else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
service.deleteAlert = function(userId, id) {
var deferred = $q.defer();
userMock.deleteAlert(userId, id).then(function(response) {
deferred.resolve(response.data);
}, function(e) {
deferred.reject('DATA ERROR');
});
return deferred.promise;
};
return service;
};
angular
.module('abp', [])
.service('userMock', userMock)
.service('userService', userService)
.controller('MyLivestockController', MyLivestockController);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="abp">
<div data-ng-controller="MyLivestockController as vm">
<div>Alerts</div>
<span data-ng-bind="vm.alertsNotification.isLoading ? 'Updating...' : vm.alertCount"></span>
<div data-ng-repeat="alert in vm.alerts">
{{alert.id}}: {{alert.message}}
<button ng-click="vm.deleteAlert(alert.id)">Delete</button>
</div>
</div>
</div>

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