AngularJS: goto previous url with refresh using $window - angularjs

I am a newbie of AngularJS using version 1.6.4, What i am trying to do is redirect user on previous page with a complete refresh. Right now i am getting back but page is not refreshing. Any idea how can i do that with a single line code.
user-login.component.js:
(function () {
"use strict";
var module = angular.module(__appName);
function controller(authService, $window, $location, $document) {
var model = this;
model.$onInit = function () {
//TODO:
};
model.login = function () {
authService.login(model.email, model.password).then(function (response) {
//$window.history.back();
//$window.history.go(-1);
//$window.location.href = '/';
console.log("url:"+$document.referrer);
//$document.referrer is showing undefined in console
$location.replace($document.referrer);
},
function (response) {
model.msg = response.error;
});
}
}
module.component("userLogin", {
templateUrl: "components/user-login/user-login.template.html",
bindings: {
email: "<",
password: "<"
},
controllerAs: "model",
controller: ["authService", "$window", "$location", "$document" controller]
});
}());
App.js:
"use strict";
//Global variables
var __apiRoot = "http://localhost:8000/api"; //No slash '/' at the end
var module = angular.module(__appName, [
"ui.router",
"angular-jwt"
]);
module.config(function ($stateProvider, $urlRouterProvider, $httpProvider, jwtOptionsProvider) {
$urlRouterProvider.otherwise('/app/home');
$stateProvider
.state("app", {
abstract: true,
url: "/app",
component: "appRouting"
})
.state("app.home", {
url: "/home",
component: "homeRouting"
})
.state("app.search", {
url: "/search/:q",
component: "searchRouting"
});
jwtOptionsProvider.config({
tokenGetter: ['authService', function (authService) {
return authService.getToken();
}],
whiteListedDomains: ['localhost']
});
$httpProvider.interceptors.push('jwtInterceptor');
});

If you are using angular-ui-router and have name of previous state then use :
$state.go('previousState', {}, { reload: true });
If you don't have the name of the previous state then you could use this piece of code it will run every time state change will occur.
$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from,fromParams) {
$rootScope.previousState = from.name;
$rootScope.currentState = to.name;
console.log('Previous state:'+$rootScope.previousState)
console.log('Current state:'+$rootScope.currentState)
});

you can refresh page by simply using native javascript. window.location.reload()

use $location.replace(). You can get the previous URL of where you came from using $document.referrer. $location.replace($document.referrer)

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

angularjs resolve is undefined

so in my state, i have
angular.module('app', ['ui.router', 'chart.js'])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/home',
component: 'home',
resolve: {
data: ['$http', function ($http) {
return $http.get('some api call')
.then(function (response) {
console.log("this is the response", response);
return response;
});
}]
}
});
}]);
then i get the proper response back. but when i check my resolve in here,
angular.module('app')
.component('home', {
templateUrl: 'Content/app/components/home.html',
bindings: {
resolve: '<'
},
controller: [
function () {
var vm = this;
vm.$onInit = function () {
console.log("this is the resolve", vm)
}
}]
});
i see that my resolve is undefined. Am i doing something wrong?
$stateProvider will bind what you specify inside the resolve object to your component, rather than binding the whole resolve object itself.
angular.module('app')
.component('home', {
templateUrl: 'Content/app/components/home.html',
bindings: {
data: '<'
},
controller: [
function () {
var vm = this;
vm.$onInit = function () {
console.log("this is the resolve", vm)
}
}]
});
Documentation link: https://ui-router.github.io/ng1/docs/latest/interfaces/state.statedeclaration.html#as-an-object

when I use ui.bootstrap, onEnter doesn't work

I built web app with angular1 and webpack2.
I want to make modal popup with own state so I used ui.router and
ui.bootstrap.
But the problem is, onEnter method doesn't work.
below is my app.js,
and I brought codes about modal at here :
Open Modal and change URL without change the view in AngularJS
import angular from 'angular';
import 'angular-ui-router';
import 'angular-ui-bootstrap';
import 'angular-resource';
// controllers
import homeController from './pages/home/home-controller';
import playerController from './pages/player/player-controller';
import toolbarController from './components/toolbar-controller';
angular.module('907dg', [
'ui.router',
'ui.bootstrap'
])
.config(($stateProvider, $locationProvider) => {
$stateProvider
.state('home', {
url: '/',
template: require('./pages/home/home.html'),
controller: 'HomeController'
})
// modal codes
.state('player', {
url: '/player/:playerName',
onEnter: function($stateParams, $state, $modal) {
console.log('here is player modal');
$modal.open({
template: '<div><h1>PLAYER MODAL POPUP</h1></div>',
resolve: {},
controller: function($scope, $state) {
$scope.ok = function () {
$scope.$close();
};
$scope.dismiss = function () {
$scope.$dismiss();
};
}
}).result.then(function (result) {
// $scope.$close
}, function (result) {
// $scope.$dismiss
}).finally(function () {
// finally
return $state.transitionTo('home');
});
}
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.controller('MasterController', ($scope) => {
$scope.greeting = 'HERE IS INDEX';
})
.filter('trustAsResourceUrl', ['$sce', function($sce) {
return function(val) {
return $sce.trustAsResourceUrl(val);
};
}]);
playerController();
homeController();
toolbarController();
and the controller that calls modal.
$scope.show = function (pName) {
$state.go('player', { playerName: pName });
};

Get DB Value In Angular Config

I have an app that uses angular. In the app.config is where I have to setup my routes, however I want to authorize my routes because not everyone who uses the app can see every page.
So I have already tried to make a factory that gives a boolean to tell the app if that person can see the route or not, and learned that I cannot inject a factory into a config.
So I have made a provider that I can inject into the config:
(function () {
'use strict';
angular.module('services')
.factory('Auth', ['$http', function AuthFactory($http) {
return {
LinkAuth: function (Name) {
return $http({ method: 'GET', url: '/Dashboard/AuthorizeNavItem', data: { Name: Name } });
}
}
}]);
angular.module('services')
.provider('AuthProvider', ['Auth', function (Auth) {
var allowed = false;
this.$get = function (Name) {
Auth.LinkAuth(Name).success(function (data) {
allowed = data.Authorized;
});
return allowed;
}
}]);
})();
My app.config:
(function () {
'use strict';
angular.module('app.it', [])
.config(['$stateProvider', 'msNavigationServiceProvider', 'AuthProvider', function ($stateProvider, msNavigationServiceProvider, AuthProvider) {
$stateProvider
.state('app.it', {
abstract: true,
url: '/information-technology',
})
.state('app.it.users', {
url: '/users',
views: {
'content#app': {
templateUrl: '/IT/Users',
controller: 'ITUserController as vm'
}
}
});
/*
We need to get a bool to say if a user is part of a group that can see this page.
*/
var allowed = true;//I want the provider $get method to return that bool here
if (allowed)
{
//This builds the navigation bar
msNavigationServiceProvider.saveItem('app.authroute', {
title: 'Authorized Route',
icon: 'icon-monitor',
weight: 2
});
//This builds the navigation bar
msNavigationServiceProvider.saveItem('app.authroute.route', {
title: 'Route',
state: 'app.authroute.route'
});
}
}]);
})();
How do I access that AuthProvider $get and store the bool in a variable in the config?

$stateChangeSuccess, always the same value of $state.params

I can't wrap my head around this, I'm really struggling with ui-routeand $stateChangeSuccess and $watch, got two issues. I'm trying to change a value of a parameter, when I change the state, click a url. I think it's important to know that I use sub-states. With my current setup I get that the $stateChangeSuccess triggers twice on load, meaning it sets the value right away. What I'm trying to do is to only have it set on change of url.
My route looks like this, I'm trying to set the value of a parameter
.state('medications', {
url: '/medications',
templateUrl: '/partials/home.html',
controller: 'mainController',
params: { showSection: false },
resolve: {
postPromise: ['medicationservice', function(medicationservice) {
return medicationservice.getAll();
}]
}
})
.state('medications.add', {
url: '/add',
templateUrl: '/partials/home.html',
controller: 'mainController',
params: { showSection: true },
})
in my controller I got the following, where I set the openSesame parameter to false explicitly on init, but as described it triggers and sets it to true.
mainModule.controller('mainController', [
'$scope',
'$state',
'$rootScope',
'medicationservice',
function($scope, $state, $rootScope, medicationservice) {
$scope.medication = {};
$scope.medications = medicationservice.posts;
$scope.openSesame = false;
$rootScope.$on("$stateChangeSuccess", function() {
$scope.openSesame = true;
console.log($scope.openSesame);
});
}]);
in my plunker the state change works once, that is if I use the $rootScope.
You can actually use $stateChangeSuccess without $injecting $rootScope. You can set a listener on the $scope object instead. Take a look at the following plunker.
And the revised code:
(function() {
var app = angular.module('myApp', ['ui.router']);
app.controller('mainController', [
'$scope',
'$state',
function($scope, $state) {
$scope.medication = {};
$scope.openSesame = false;
$scope.$on('$stateChangeSuccess',function(event, toState){
$scope.openSesame = toState.params.showSection;
});
$scope.triggerMe = function() {
alert('yes');
};
}
]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('medications', {
url: '/medications',
template: '<div>{{openSesame}}</div>',
controller: 'mainController',
params: {
showSection: false
}
})
.state('medications.add', {
url: '/add',
template: '<div>{{openSesame}}</div>',
controller: 'mainController',
params: {
showSection: true
},
});
$urlRouterProvider.otherwise('medications');
}
]);
}());
Click your buttons medication and medication add to see the value change.
The callback of $stateChangeSuccess, you have access toState, fromState. Or check current state name
$rootScope.$on("$stateChangeSuccess", function() {
if ($state.current.name == "medications.add") {
$scope.openSesame = true;
}
console.log($scope.openSesame);
});

Resources