Redirection error in angularjs - angularjs

After adding data in location table, clicking on the save button should redirect it to list of data in location table.But ,it stays in the same page after adding.The same path is given to modify location,it works fine. whereas the same path does not redirect when add location.
function locationController($scope, $state, $rootScope, locationServices,$location, locations, location, primaryLocation, $stateParams,locationTypes, countries) {
var vm = this;
$scope.locations = locations.data;
$scope.location = location.data;
if (primaryLocation.data && primaryLocation.data[0])
$scope.primaryLocation = primaryLocation.data[0];
if (!$scope.location) {
var location = {};
if ($stateParams.accountId) {
$scope.location = {accountId: $stateParams.accountId };
} else {
$scope.location = location;
}
}
$rootScope.title = "Locations";
$scope.locationslist = "views/locations.html";
$scope.addOrModifyLocation = function (location) {
if (location._id) {
locationServices.modifyLocation(location).then(function (response) {
$location.path('/account/locations/contacts/' + location.accountId + '/' +location.accountId);
// $state.reload();
})
} else {
location.status = 'ACTIVE';
locationServices.addLocation(location).then(function (response) {
$location.path('/account/locations/contacts/' + location.accountId + '/' +location.accountId);
})
}
};

If you want angular to know about your $location update, you have to do it like this :
$rootScope.$apply(function() {
$location.path("/my-path"); // path must start with leading /
});
If you're using ui-router, a cleaner approach would be to use
$state.go('stateName', {'accountId' : location.accountId, });
edit :
If you have errors that happen during a state change, you can see it by adding the following code in your app after declaring your module :
angular.module("appName").run([
"$rootScope",
function ($rootScope) {
$rootScope.$on("$stateChangeError", function(error) {
console.log(error);
});
}
]);

Related

AngularJS Dynamically Load Controller and Template based on Route

I am trying to dynamically load BOTH a template and controller based on the route (in Angular 1.6), pulling from the current directory architecture.
app
|__login.module.js
|__home.controller.js
|__login.factory.js
|__home.view.html
|__404.view.html
|__index.html
Currently, the below code works to pull the proper template, but the controller won't load:
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
function getController(routeParams){
//I think I need a promise here, but I don't know how to write it
routeParams = routeParams.route.split('/').join('.');
return routeParams + 'controller';
}
$routeProvider.when('/:route*', {
controller: function($routeParams) { //does not work
return getController($routeParams);
},
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
I understand that controllers need to be present at the start of the app, but I am unable to write a proper resolve with a promise statement.
Can someone help me right a resolve with a simple promise that returns a string of the controller name based on the route?
I was able to get it working by not including the controller in the routing at all. Instead I put the ng-controller attribute in the view I was loading.
This worked!
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
$routeProvider.when('/:route*', {
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
In the HTML of that view, I just put ng-controller="home.controller"(or whatever controller is appropriate)

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

Common service for sessionstorage in angularjs

Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.

iOS emulator GPS does not work?

I tested my app in the iOS emulator and noticed that the gps does not work.
In the emulator I set the location to "Apple"
and installed the corodova plugin by: "cordova plugin add org.apache.cordova.geolocation".
Here is my Code:
angular.module('home', ['services'])
.controller('homeCtrl',
function ($scope, $location, $state, serverAPI, $ionicPopup) {
$scope.buttonType = "icon ion-search";
$scope.buttonDisable = false;
$scope.text = 'Search';
var UID = JSON.parse(window.localStorage.getItem('Credentials')).UID;
serverAPI.getUserData(UID, function (data) {
$scope.userName = data.userName;
$scope.points = data.points;
$scope.fotoId = data.fotoId;
console.log(data);
});
$scope.click = function () {
$scope.buttonDisable = true;
$scope.text = 'Searching';
$scope.buttonType = 'icon ion-loading-a';
// //Grap geoLocation
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
};
var saveGeoData = function (geoData) {
console.log("nach geo");
var myPosition = {
'longitude': geoData.coords.longitude,
'latitude': geoData.coords.latitude
};
console.log("ss");
console.log(myPosition.latitude);
window.localStorage.setItem('myPosition', JSON.stringify(myPosition));
//If geoloaction is saved successfully => Send geodata to server to receive teammate
sendToServer(myPosition);
}
//Send current location to Server to receive teammate
var sendToServer = function (myPosition) {
serverAPI.searchPartnerToPlayWith(myPosition.longitude, myPosition.latitude, UID, function (data) {
//No other players around you. Server returns -1
if (data == -1) {
$ionicPopup.alert({
title: 'Too bad :(',
template: 'Unfortunateley there are no other players around you. Try it some other time!'
});
} else {
window.localStorage.setItem('teammate', data.username);
window.localStorage.setItem('isEnummeration', data.taskType);
window.localStorage.setItem('task', data.task);
var teammatePosition = {
'longitude': data.longitude,
'latitude': data.latitude
};
window.localStorage.setItem('teammatePosition', teammatePosition);
//TODO: data.fotoId => request foto from server
$state.go('tab.play-screen');
}
})
}
};
})
When the function click is called, it just stops in Line:
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
Do you have a guess whats my problem? In the browser it works just fine.
Thanks!
Make sure you include this file into your project.
https://github.com/apache/cordova-plugin-geolocation/blob/master/www/geolocation.js
It can be high probability cause from there, this function not exist in your project, getCurrentPosition.

Back Arrow and Angular Routing - Press Back Twice

Angularv1.1.5
Site: http://tilsa.azurewebsites.net
I have a very simple route setup however when the user goes from the default/home route to the detail (pregunta) route and then clicks the back button nothing happens. The 2nd/3rd time the back button is clicked the user returns (chrome) to the default/home route. I'm not sure as to how or why this is happening.
$routeProvider.
when('/', {
templateUrl: '/js/app/partial/index.html',
controller: 'IndexCtrl'
})
.when('/pregunta/:id', {
templateUrl: '/js/app/partial/detalle.html',
controller: 'PreguntaDetalleCtrl'
}).
otherwise({
redirectTo: '/'
});
Here are the two relevant controllers. I've removed some of the code that doesn't seem relevant (polling for new info/etc):
// load the index list of questions, the actual questions are loaded in parent scope
.controller('IndexCtrl', ['$scope', 'services', 'data', '$modal', 'navigation', 'timeFunctions', function ($scope, services, data, $modal, navigation, timeFunctions)
{
$scope.noEncodeUrl = 'http://tilsa.azurewebsites.net/';
$scope.url = encodeURIComponent($scope.noEncodeUrl);
// controls the back arrow visibility to go back
navigation.setReturn(false);
}])
.controller('PreguntaDetalleCtrl', ['$scope', '$routeParams', 'services', 'navigation', 'graphService', 'stringFx', '$timeout', 'timeFunctions', function ($scope, $routeParams, services, navigation, graphService, stringFx, $timeout, timeFunctions) {
$scope.notas = [];
$scope.comentario = '';
navigation.setReturn(true);
$scope.loadPregunta = function (id, loadComments)
{
services.preguntas.getDetalle(id).then(function (data)
{
$scope.safeApply(function ()
{
$scope.pregunta = data;
graphService.setProp('title', $scope.pregunta.pregunta);
$scope.noEncodeUrl = 'http://tilsa.azurewebsites.net/pregunta/' + id;
$scope.url = encodeURIComponent($scope.noEncodeUrl);
$scope.preguntaText = stringFx.removeAccent('¿'+$scope.pregunta.pregunta+'?');
});
if (loadComments)
{
$scope.commentTracker = {
defaults: { },
skip: 0,
take: 20
};
$scope.$on('$destroy', function (e)
{
$scope.stopPolling();
});
$scope.startPolling = function ()
{
// scrollTimeout will store the unique ID for the $setInterval instance
return $scope.scrollTimeout = timeFunctions.$setInterval(poll, 10000, $scope);
// Function called on interval with scope available
function poll($scope)
{
services.preguntas.getNotas($scope.pregunta.id, $scope.commentTracker, $scope.notas).then(function (data)
{
$scope.safeApply(function ()
{
for (i = 0, l = data.notas.length; i < l; i++)
{
$scope.notas.unshift(data.notas[i]);
}
});
});
}
}
$scope.stopPolling = function ()
{
return timeFunctions.$clearInterval($scope.scrollTimeout);
}
$scope.startPolling();
$scope.cargarAnteriores = function ()
{
//$scope.commentTracker.skip++;
services.preguntas.getNotas($scope.pregunta.id, $scope.commentTracker, $scope.notas, true).then(function (data)
{
$scope.safeApply(function ()
{
$scope.notas = $scope.notas.concat(data.notas);
$scope.masNotas = $scope.notas.length > 0;
});
});
}
$scope.cargarAnteriores();
}
});
}
$scope.notaNueva = function () {
//$scope.commentario;
if ($scope.comentario.length < 3)
{
alert('Escribe algo mas, no seas tacano con tus palabras');
return;
}
$scope.processing = true;
services.preguntas.insertNota($scope.pregunta.id, $scope.comentario, $scope.notas, false).then(function (data)
{
$scope.comentario = '';
$scope.processing = false;
$scope.loadPregunta($scope.pregunta.id, false);
services.preguntas.getNotas($scope.pregunta.id, $scope.commentTracker, $scope.notas).then(function (data)
{
$scope.safeApply(function ()
{
for (i = 0, l = data.notas.length; i < l; i++)
{
$scope.notas.unshift(data.notas[i]);
}
});
});
});
}
$scope.loadPregunta($routeParams.id, true)
$scope.$on('updatedpregunta', function (event, obj)
{
$scope.loadPregunta(obj, false)
});
}]);
I had this issue as well! Turned ut that artur grzesiak was right! I had a iframe on my page that had a binding for its src-attribute.
<iframe src="{{selected.url}}"></iframe>
Since the default value of $scope.selected.url was null the first thing that happened was that it was loading a url called null.
After some research I found that there was a special directive for the iframe:
<iframe ng-src="{{selected.url}}"></iframe>
This change solved my is
It seems that the Angular side of your app is fine.
99% the problem is caused by some external library. For sure there is some problem with this script kVEquaeit4R (it seens to be a facebook plugin), as it fails to load some resource (404 error): The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. and as a consequence a couple of further errors are generated (look at the console). And in turn it prevents the app from calling window.location.hostname.replace what actually is present in the kVEquaeit4R script.
So my suggestion is as follow: remove this fb plugin from your site and check if the routing works properly...

Resources