I have ng-click button when I click on it, I run an ajax call like the following:
function Click(data){
var obj = {'data':data};
return $http({
method: "POST",
url:("x.php"),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({data:obj}),
})
.then(complete)
.catch(function(message) {
throw new Error("XHR Failed ",message);
});
function complete(data, status, headers, config) {
}
}
then I am trying to navigate to another route while the ajax call is still running and I get a message:
Do you want to leave the site?
I don't want pop up like that at all.
I tried to put window.onbeforeunload = null; in each page but it is not working
How can I disable it?
Also, sometime I get a refresh popup.
My routing:
// Optimize load start with remove binding information inside the DOM element
$compileProvider.debugInfoEnabled(true);
// Set default state
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: "/",
templateUrl: "x.php",
controller: 'xController',
controllerAs: 'vm',
resolve: {
fun: function(x) {
return x.get();
}
}
});
$httpProvider.interceptors.push('saHttpActivityInterceptor');
Related
I try to implement a remember-login function to my AngularJS / ionic mobile app
the problem:
the login page is allways loaded before the automatic login is finished and the transition starts, so you can see the login page for a moment.
question:
is there an event like 'pagebeforeshow' in JQM or another method to directly load the 'home' state?
I use:
ionic 1.3.1
angular 1.5.3
cordova 4.0.0
code examples:
LoginController:
function LoginController($scope, $http, $ionicModal, $state, $SessionStorage) {
var vm = this;
activate();
function activate(){
vm.staylogged = JSON.parse(localStorage.staylogged || null);
if(vm.staylogged){
vm.remember = vm.staylogged; //vm.remember: checkbox in login form
login();
}else{
// get some data from the server
}
}
function login(){
if(vm.staylogged){
//get login informations from localStorage
}
$http({
method: 'POST',
url: vm.server +"?=GetLogin",
headers: {
'Content-Type': 'text/xml; charset=\"utf-8\"'
},
data: soa
}).then(function successCallback(response) {
if(response.returnCode == 0){
localStorage.setItem('staylogged', JSON.stringify(vm.remember));
// safe login informations to local Storage for next use
$state.go('tabs.home');
}
}, function errorCallback(response) {
console.log(response);
});
}
}
You can do following way -
In app.js
.state('signin', {
url: '/sign-in',
templateUrl: 'templates/views/login.html',
controller: 'LoginController',
resolve: {
// Do your code here will execute before page render
}
})
I have the following states as part of an AngularJS app:
.state('app.stages', {
url: '/stages',
views: {
'menuContent': {
templateUrl: 'templates/stages.html',
controller: 'StagesCtrl'
}
}
})
.state('app.stage', {
url: '/stages/:stageId',
views: {
'menuContent': {
templateUrl: 'templates/stage.html',
controller: 'StageCtrl'
}
}
The controllers associated are:
controller('StagesCtrl', function($scope,$http) {
$http.get("http://localhost/apistages")
.then(function(response) {
$scope.stages = response.data;
});
})
.controller('StageCtrl', function($scope, $http, $stateParams) {
$http({
method: 'GET',
url: 'http://localhost/apistage/',
params: {stageId: $stateParams.stageId}
}).then(function successCallback(response) {
$scope.stage = response.data;
}, function errorCallback(response) {
});
});
The stages list works well, but the query in the stage controller tries to access http://localhost/apistage/?stageId=43 which results in a 500 (Internal Server Error).
The URL format that I need to use is http://localhost/apistage/43 . How can I adjust the query to fetch that URL?
Then don't use params options on $http GET request. Instead just use simple string concatenation on URL while making call to service
$http({
method: 'GET',
url: 'http://localhost/apistage/'+$stateParams.stageId //append state parameter in URL itself
})
For REST API I'd highly recommend you to use ngResource($resource) module of angular. Which has good capability to deal with rest calls.
You should not use two controllers. Use only one controller and use $routeParams to get the url parameter. Here now you check if parameter is present or not and differentiate your logic as required. You can use the following code:
var stageId = $routeParams.stageId;
If(stageId)
Do something
else
Do something different
Everytime when I make View redirect (I use href to do so) I can see that AngularJS runs GetAjaxData1, GetAjaxData2.
In the other words: instead of the single initial request to the server, I do it everytime when I make View redirection. What is wrong?
Here is my AngularJS code:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
var factory = {};
data1 = [];
data2 = [];
factory.getAjaxData1 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data1 = result;
}
});
return data1;
};
factory.getAjaxData2 = function () {
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: false,
success: function (result) {
data2 = result;
}
});
return data2;
}
};
var controllers = {};
controllers.uController = function ($scope, $location, uFactory) {
$scope.data1 = uFactory.getAjaxData1();
$scope.data2 = uFactory.getAjaxData2();
};
You definitely have to read about $http and ng-resource library and
try more angular way in your application and you also should
understand that ajax request is always asynchronous, and try to
understand promise pattern.
Technically - what you need is a caching - no matter how you are going to implement this - you need to make a single call to the API and the to cache variable.
I don't like idea of usage $.ajax, but it can look like this:
angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: 'UController',
templateUrl: '/Partial/View1.html'
}).when('/View2', {
controller: 'UController',
templateUrl: '/Partial/View2.html'
}).otherwise({redirectTo: '/View3'});
}]).factory('uFactory', function () {
return {
getFirstPromise: function () {
if (!this.$$firstPromise) {
this.$$firstPromise = $.ajax({
url: url,
type: 'GET',
contentType: "application/json"
}).then(function (data) {
window.data1 = data;
});
}
return this.$$firstPromise;
}
... //some other code
}
});
var controllers = {
uController: function ($scope, $location, uFactory) {
uFactory.getFirstPromise().then(function (data) {
$scope.data1 = data;
});
// same for other data - and don't try to make ajax requests synhronous ;-)
}
};
Controllers are not singletons. So your "UController" is created everytime your view changes. I assume that the factory is used inside this controller. See: What is the lifecycle of an AngularJS Controller?
i have one issue regarding redirecting path in angular.js.I am explaining my code below.
profileController.js:
if($('#addProfileData')[0].defaultValue=='Update'){
var updatedata={'colg_name':$scope.colgname,'address':$scope.address,'cont_no':$scope.contno,'profile_id':id};
console.log('userupdate',userdata);
$http({
method: 'POST',
url: "php/profile/updateProfileData.php",
data: updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data);
$location.path('.profile');
},function errorCallback(response) {
alert(response.data);
});
}
}
here i am setting path to profile page inside success callback function.But it is redirecting to the root page after update the data.
loginRoute.js:
var Admin=angular.module('Channabasavashwara',['ui.router']);
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'dashboardview/login.html',
controller: 'loginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboardview/dashboard.html',
controller: 'dashboardController'
})
.state('dashboard.profile', {
url: '/profile?p_i',
templateUrl: 'dashboardview/profile.html',
controller: 'profileController'
})
.state('dashboard.dept', {
url: '/dept?d_i',
templateUrl: 'dashboardview/dept.html',
controller: 'deptController'
})
.state('dashboard.princpal', {
url: '/princpal?pr_i',
templateUrl: 'dashboardview/princpal.html',
controller: 'princpalController'
})
.state('dashboard.dept_head', {
url: '/dept_head?dh_i',
templateUrl: 'dashboardview/depthead.html',
controller: 'deptheadController'
})
})
Here after update data successfully it is redirecting to login.html page.I need after updating the data the page should redirect to profile.html page.Please help me.
Try replacing the line of code with $location.path('dashboard.profile');
That would do the need for you
You can use $state instead of $location as follows:
$state.go('dashboard.profile')
Also, don't forget to inject the $state service in your controller.
If you want to use $location.path you need to use the url instead of state.
we are trying to get data from service agrService with $http its working but when i reccive data to controller i am not able to access it outside that function
$scope.resource return data inside function but not outside please help.
var app = angular.module('app', ['ui.router','ngTasty']);
app.config(['$urlRouterProvider', '$stateProvider',function($urlRouterProvider, $stateProvider, $routeProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/home.html',
controller: function($scope, $http, $location, agrService) {
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
}, function(error) {
// do something else
});
I NEED TO ACCCESS DATA HERE CAN ANY BODY HELP
console.log($scope.resource);
}
});
}]);
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
var ret = $q.defer();
$http({
method: 'GET',
dataType: "json",
url: dataUrl
})
.success(function(data, status, headers, config) {
ret.resolve(data);
}).error(function(data, status, headers, config) {
ret.reject("Niente, Nada, Caput");
});
return ret.promise;
};
});
My suggestion would be to rethink the logic a bit. You want to do something with the data after you receive it, so why not make a function that you call once the data is received?
You'll never be able to access the resource data in that console log, simply because $http is an async call, and no matter if you return a promise or not, it's simply not ready at that point.
However, if you use it in a template or elsewhere that uses angular's double binding, it will work just fine.
To fix your issue, you can define a function with what happens after that service call and simply call it from the success callback:
agrService.bannerSlides().then(function(data) {
//its working here
$scope.resource = data;
myAfterFunction(); // <--- here
}, function(error) {
// do something else
});
and the function can be:
function myAfterFunction() {
console.log($scope.resource);
}
And btw. your service is an example of deferred antipattern, you can simply do this:
app.service('agrService', function($q, $http) {this.bannerSlides = function() {
var dataUrl = 'http://WWW.EXP.COM/codeIgniter_ver/main/home';
return $http({
method: 'GET',
dataType: "json",
url: dataUrl
})
};
});