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
Related
Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.
angular.module('authentication.service', [
])
.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {
var ABCKey;
var setAuthenticatedAccount = function (account, tokenAuth) {
var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
var abc = CryptoJS.enc.Base64.parse(account.abc);
Authentication.setABCKey(abc);
console.log(Authentication.showABCKey())
}
var getAuthenticatedAccount = function() {
if(!$cookies.authenticatedAccount) {
return;
}
console.log(Authentication.showABCKey())
}
var setABCKey = function(key) {
ABCKey = key;
};
var showABCKey = function() {
return ABCKey;
};
var Authentication = {
setAuthenticatedAccount: setAuthenticatedAccount,
getAuthenticatedAccount: getAuthenticatedAccount,
setABCKey: setABCKey,
showABCKey: showABCKey
};
return Authentication;
}]);
Remove Authentication while you are calling your functions because it is creating object every time. And also set var ABCKey=null at the time of decelaration like this-
angular.module('authentication.service', [
])
.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {
var ABCKey=null;
var setAuthenticatedAccount = function (account, tokenAuth) {
var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
var abc = CryptoJS.enc.Base64.parse(account.abc);
setABCKey(abc);
console.log(showABCKey())
}
var getAuthenticatedAccount = function() {
if(!$cookies.authenticatedAccount) {
return;
}
console.log(showABCKey())
}
var setABCKey = function(key) {
ABCKey = key;
};
var showABCKey = function() {
return ABCKey;
};
var Authentication = {
setAuthenticatedAccount: setAuthenticatedAccount,
getAuthenticatedAccount: getAuthenticatedAccount,
setABCKey: setABCKey,
showABCKey: showABCKey
};
return Authentication;
}]);
dont use var its single tone class you need to define ABCkey in this
var ABCKey;
try with this
this.ABCKey = '';
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.
I need to pass a selected value from a directive that I am using in several places. It is a select input field that I need to get a selected value from.
This is how the directive looks like:
angular.module('quiz.directives')
.directive('fancySelect', function($rootScope, $timeout) {
return {
restrict: 'E',
templateUrl: 'templates/directives/fancySelect.html',
scope: {
title: '#',
model: '=',
options: '=',
multiple: '=',
enable: '=',
onChange: '&',
class: '#'
},
link: function(scope) {
scope.showOptions = false;
scope.displayValues = [];
scope.$watch('enable', function(enable) {
if (!enable && scope.showOptions) {
scope.toggleShowOptions(false);
}
});
scope.toggleShowOptions = function(show) {
if (!scope.enable) {
return;
}
if (show === undefined) {
show = !scope.showOptions;
}
if (show) {
$rootScope.$broadcast('fancySelect:hideAll');
}
$timeout(function() {
scope.showOptions = show;
});
};
scope.toggleValue = function(value) {
if (!value) {
return;
}
if (!scope.multiple) {
scope.model = value;
console.log(scope.model);
return;
}
var index = scope.model.indexOf(value);
if (index >= 0) {
scope.model.splice(index, 1);
}
else {
scope.model.push(value);
}
if (scope.onChange) {
scope.onChange();
}
};
scope.getDisplayValues = function() {
if (!scope.options || !scope.model) {
return [];
}
if (!scope.multiple && scope.model) {
return scope.options.filter(function(opt) {
return opt.id == scope.model;
});
}
return scope.options.filter(function(opt) {
return scope.model.indexOf(opt.id) >= 0;
});
};
$rootScope.$on('fancySelect:hideAll', function() {
scope.showOptions = false;
});
}
};
});
When I do console.log(scope.model); I get the selected value, but I am not sure how to get it and use it in my controller?
This is the controller:
angular.module('quiz.controllers')
.controller('ProfileController', function(
$scope,
$state,
$stateParams,
UserService,
$auth,
MessageService,
$ionicLoading,
AppSettings,
$timeout,
AvatarService,
PushService,
$http
) {
$scope.user = UserService.get();
$scope.profilePromise = {};
if ($scope.user.player.avatar == ""){
$scope.user.player.avatar = AvatarService.getRandom();
}
$http.get(AppSettings.apiUrl + '/years')
.then(function(result) {
$scope.years = result.data;
});
$scope.updateUser = function(form) {
if (!form.$valid) {
var message = "Ugyldig data i skjema. Sjekk felter markert med rødt.";
MessageService.alertMessage(message);
return;
}
saveUser($scope.user);
};
$scope.getNextAvatar = function() {
$scope.user.player.avatar = AvatarService.getNext($scope.user.player.avatar);
};
$scope.getPreviousAvatar = function() {
$scope.user.player.avatar = AvatarService.getPrevious($scope.user.player.avatar);
};
var saveUser = function(user) {
$scope.profilePromise = UserService.save(user);
$scope.profilePromise.then(function(result) {
$scope.user = result.data.user;
PushService.init();
PushService.getDeviceId().then(function(id) {
UserService.addDevice(id);
});
if ($stateParams.register) {
$state.go('main.front');
}
}, function(error) {
var message = "Kunne ikke lagre bruker. Melding fra server: " + error.data.message;
MessageService.alertMessage(message);
});
};
});
You already have an onChange binding in the scope, so why don't you use that one?
In your directive:
if (scope.onChange) {
scope.onChange({ $value: scope.model });
}
Then pass a controller function to your directive:
<fancy-select on-change="onChange($value)"></fancy-select>
In your controller:
$scope.onChange = function(val) {
// do something with the value
}
I'm using angular module ng-table (http://ngmodules.org/modules/ng-table) in my rails - angular app. The problem is, ng-table is duplicating part of a path in my URLs.
E.G.: The URL should be http://host.com/hostings/1/email-accounts but somewhere in the module it becomes http://host.com/hostings/1/email-accounts#/email-accounts.
My application works in following way:
User visits http://host.com/hostings/1/email-accounts
Rails renders a view with ng-controller directive and some basic layout(in this case, ng-controller="EmailAccountsCtrl")
Angular controller populates the view
Bottom line: I'm not using angular for routing.
This is my angular config:
admin = angular.module('admin', ['ngResource', 'hostingsModule', 'ui.bootstrap.modal', 'ui.bootstrap.datepicker']);
admin.config(function($locationProvider, $httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = 'https://sadmin.igloonet.cz'
});
EmailAccountsCtrl:
hostingsModule.controller('EmailAccountsCtrl', ['$scope', '$q', '$filter', 'Hosting', 'EmailAccount', 'ngTableParams', function($scope, $q, $filter, Hosting, EmailAccount, ngTableParams) {
var hostingId;
$scope.emailAccounts = [];
$scope.hosting = findHosting(hostingId);
$scope.tableParams = new ngTableParams({
$liveFiltering: true,
page: 1,
total: 0,
count: 10,
sorting: {
email: 'asc'
}
});
$scope.$watch('tableParams', function(params) {
if (angular.equals({},params.filter)) {
$scope.tableParams.disabledButton = true;
} else {
$scope.tableParams.disabledButton = false;
}
$scope.loading = true;
EmailAccount.all(hostingId, params.url()).success(function(data) {
$scope.loading = false;
$scope.emailAccounts = data.emailAccounts;
$scope.tableParams.total = data.total;
});
});
}]);
And a part of a controller of ng-table directive:
controller: [
"$scope", "$timeout", function($scope, $timeout) {
var updateParams;
$scope.params = $scope.params || {
page: 1,
count: 10
};
// When I log the url here, it's still correct
$scope.$watch('params.filter', (function(value) {
// When I log the url here, it has the part with #email-accounts already appended
if ($scope.params.$liveFiltering) {
console.log(updateParams());
updateParams(value);
return $scope.goToPage(1);
}
}), true);
updateParams = function(newParams) {
newParams = angular.extend($scope.params, newParams);
$scope.paramsModel.assign($scope.$parent, new ngTableParams(newParams));
return $scope.params = angular.copy(newParams);
};
$scope.goToPage = function(page) {
if (page > 0 && $scope.params.page !== page && $scope.params.count * (page - 1) <= $scope.params.total) {
return updateParams({
page: page
});
}
};
$scope.changeCount = function(count) {
return updateParams({
page: 1,
count: count
});
};
$scope.doFilter = function() {
return updateParams({
page: 1
});
};
return $scope.sortBy = function(column) {
var sorting, sortingParams;
if (!column.sortable) {
return;
}
sorting = $scope.params.sorting && $scope.params.sorting[column.sortable] && ($scope.params.sorting[column.sortable] === "desc");
sortingParams = {};
sortingParams[column.sortable] = (sorting ? "asc" : "desc");
return updateParams({
sorting: sortingParams
});
};
}
],
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