AngularJS: ui-router secured states - javascript

I have one main controller for my app - AppCtrl and use ui-router. How can I make secured states?
$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
var authorization = toState.data.authorization;
if(!Security.isAuthenticated() && authorization != false)
$location.path('/login');
});
For example I want to make books and authors states secured, and login state not secured.
.state('login', {
url: '/login',
templateUrl: /**/,
controller: /**/,
data: {
authorization: false
}
})
.state('books', {
url: '/books',
templateUrl: /**/,
controller: /**/,
data: {
authorization: true
}
})
.state('authors', {
url: '/authors',
templateUrl: /**/,
controller: /**/,
data: {
authorization: true
}
})
Security.isAuthenticated() function returns boolean. When I open /books everything works perfectly, page are being redirected to /login, when after redirecting I open /authors, page loads and it's content are shown, but browser's url is /login, so page being redirected, but somehow it's content are shown.

Figured out that I have to prevent opening next route, and go to login state. Made some changes and all works perfectly.
if (!Security.isAuthenticated() && authorization != false){
event.preventDefault();
$state.go('login');
}

Related

How to prevent user logging out when refreshing the page in an Angular(Client) and Loopback(Server) application?

I have a Loopback.io SPA with an Angular client. I followed the official Loopback Documentation https://loopback.io/doc/en/lb2/Create-AngularJS-client.html
The problem is that when I refresh the page in the browser, the client is logging out. It seems that the currentUser variable is not restored after the refresh. How could I solve this?
Here are the auth.js and app.js files:
js/services/auth.js
angular
.module('app')
.factory('AuthService', ['Reviewer', '$q', '$rootScope', function(User, $q,
$rootScope) {
function login(email, password) {
return User
.login({
email: email,
password: password
})
.$promise
.then(function(response) {
$rootScope.currentUser = {
id: response.user.id,
tokenId: response.id,
email: email
};
});
}
function logout() {
return User
.logout()
.$promise
.then(function() {
$rootScope.currentUser = null;
});
}
function register(email, password) {
return User
.create({
email: email,
password: password
})
.$promise;
}
return {
login: login,
logout: logout,
register: register
};
}]);
client/js/app.js
angular
.module('app', [
'ui.router',
'lbServices'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('add-review', {
url: '/add-review',
templateUrl: 'views/review-form.html',
controller: 'AddReviewController',
authenticate: true
})
.state('all-reviews', {
url: '/all-reviews',
templateUrl: 'views/all-reviews.html',
controller: 'AllReviewsController'
})
.state('edit-review', {
url: '/edit-review/:id',
templateUrl: 'views/review-form.html',
controller: 'EditReviewController',
authenticate: true
})
.state('delete-review', {
url: '/delete-review/:id',
controller: 'DeleteReviewController',
authenticate: true
})
.state('forbidden', {
url: '/forbidden',
templateUrl: 'views/forbidden.html',
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'AuthLoginController'
})
.state('logout', {
url: '/logout',
controller: 'AuthLogoutController'
})
.state('my-reviews', {
url: '/my-reviews',
templateUrl: 'views/my-reviews.html',
controller: 'MyReviewsController',
authenticate: true
})
.state('sign-up', {
url: '/sign-up',
templateUrl: 'views/sign-up-form.html',
controller: 'SignUpController',
})
.state('sign-up-success', {
url: '/sign-up/success',
templateUrl: 'views/sign-up-success.html'
});
$urlRouterProvider.otherwise('all-reviews');
}])
.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, next) {
// redirect to login page if not logged in
if (next.authenticate && !$rootScope.currentUser) {
event.preventDefault(); //prevent current page from loading
$state.go('forbidden');
}
});
}]);
scope in angularjs after refresh page initial, and not save old value before refresh
you can save token in local storage browser (or cookie) and in load page set scope

How to handle the authentication using 3rd party login in Angularjs

By running the code below, the authentication window pops-up and the user confirms the login. This part works. Once the authorize button is clicked, this redirects to the previous tab in the same window (in the pop-up not in the parent window). How I can close this pop-up window after authorization is confirmed by the user and how can I get back the authorization code from the url? For instance in the code below, the first "console.log(event.url);" is not executed.
var redirectUri = "http://localhost:8100/callback";
var ref = window.open('https://www.example.com/oauth/authorize?client_id=' + clientID + '&redirect_uri=' + redirectUri + '&scope=write&response_type=code&approval_prompt=force', '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');
ref.addEventListener('loadstart', function (event) { // THIS IS NOT TRIGGERED FOR SOME REASON
console.log(event.url);
if ((event.url).indexOf(redirectUri) === 0) {
requestToken = (event.url).split("code=")[1];
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({
method: "post",
url: "https://www.example.com/oauth/token",
data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken
})
.success(function (data) {
$scope.data = data;
console.log(event.url);
})
.error(function (data, status) {
deferred.reject("Problem authenticating");
});
}
});
Below are the tabs used in the application. How can I return to my tab.example after callback?
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tab.example', {
url: '/example',
views: {
'tab-example': {
templateUrl: 'templates/tab-example.html',
controller: 'ExampleAPICtrl'
}
}
})
.state('callback', {
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/');
You need a service to wrap the 3rd party Provider so it can listen for the event Call back.
a great library implementation I've used:
mrzmyr Angular-Google-Plus
The heart of the librarie's approach is in the following code snippet:
NgGooglePlus.prototype.login = function () {
deferred = $q.defer();
gapi.auth.authorize({
client_id: options.clientId,
scope: options.scopes,
immediate: false,
approval_prompt: "force",
max_auth_age: 0
}, this.handleAuthResult);
return deferred.promise;
};
When you want to do login with 3rd party, i advice you to create a login service which will perform the login by sending the good information to the login system (other API, web application with url...).
Like that, your service can emit event that can be used in your application to perform more action
$scope.$broadcast('loadstart', {
someProp: 'send parameter to your event in the data object'
});
$scope.$on('loadstart', function (event, data) {
//your function the tretment of the reply
});
If you want to go forward with the event you can follow this link : https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
to return in your tab.example you can try the $state in the .success part of your http request. This service allow you to choose on which state you want to be :
$state.go('tab.example');

app is re-initializing the first time ADAL "protected" URL is accessed via $http

I have page based loosely off the Angular SPA ADAL sample found here
After returning from the MS login page upon accessing my API that is secured with AAD the angular .config() function is called 3 times. This breaks updates to scope that was initiated in the first instance of the app. After this initial thrashing everything works as expected. Even reloading the page does not reproduce this issue. It only occurs this first time after logging in.
It this normal with ADAL? Is there a way to avoid this?
Am I not updating $scope correctly from AJAX call backs?
Below is some key code snippets:
app.js:
'use strict';
angular.module('app', ['ngRoute', 'AdalAngular'])
.config(['$routeProvider', '$httpProvider', 'adalAuthenticationServiceProvider', '$locationProvider', function ($routeProvider, $httpProvider, adalProvider, $locationProvider) {
$routeProvider.when("/visit", {
controller: "visitCtrl",
templateUrl: "/ngViews/Visit.html",
requireADLogin: false,
}).when("/visit/:visitNumber", {
controller: "visitCtrl",
templateUrl: "/ngViews/Visit.html",
requireADLogin: false,
}).when("/", {
controller: "homeCtrl",
templateUrl: "/ngViews/Home.html",
requireADLogin: false,
}).when("/teamwork", {
controller: "teamworkCtrl",
templateUrl: "/ngViews/Teamwork.html",
requireADLogin: false,
}).when("/mywork", {
controller: "myWorkCtrl",
templateUrl: "/ngViews/MyWork.html",
requireADLogin: false,
}).when("/dashboard", {
controller: "dashboardCtrl",
templateUrl: "/ngViews/Dashboard.html",
requireADLogin: false,
}).when("/error", {
templateUrl: "/ngViews/Error.html",
controller: "errorCtrl",
requireADLogin: false,
});
$routeProvider.otherwise({ redirectTo: '/' }); // needed to avoid a bug in ADAL see: https://github.com/AzureAD/azure-activedirectory-library-for-js/issues/42
var endpoints = cmSettings.adalEndpoints;
//$locationProvider.html5Mode(true); // breaks ADAL
adalProvider.init(
{
instance: cmSettings.aadInstance,
tenant: cmSettings.tenant,
clientId: cmSettings.clientId,
extraQueryParameter: 'nux=1',
endpoints: endpoints,
cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
// Also, token acquisition for the To Go API will fail in IE when running on localhost, due to IE security restrictions.
},
$httpProvider
);
}]);
controller:
'use strict'
angular.module('app')
.controller('navBarCtrl', ['$scope', '$location', 'visitsSvc', '$timeout', function ($scope, $location, visitsSvc, $timeout) {
$scope.myWorkCount = 0;
$scope.teamworkCount = 0;
$scope.loading = false;
var updateVisitCount = function () {
$scope.loading = true;
$scope.$on("cm:myVisitsReceived", function (event, args) {
$timeout(function () {
if (args.data) {
$scope.myWorkCount = args.data.length;
}
$scope.loading = false;
});
});
$scope.$on("cm:teamVisitsReceived", function (event, args) {
$timeout(function () {
if (args.data) {
$scope.teamworkCount = args.data.length;
}
$scope.loading = false;
});
});
visitsSvc.getMyVisits();
visitsSvc.getTeamVisits();
}
if ($scope.userInfo.isAuthenticated && !$scope.loading) {
updateVisitCount();
} else {
$scope.$on("adal:loginSuccess", function (scope) {
updateVisitCount();
});
}
}]);
data service:
angular.module('app')
.factory('visitsSvc', ['$http', '$rootScope', function ($http, $rootScope) {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
return {
getMyVisits: function () {
$http.get(cmSettings.apiUrl + '/api/v1/visits/my').success(function (data, status, headers, config) {
$rootScope.$broadcast("cm:myVisitsReceived", { data: data, status: status, success: true });
})
.error(function (data, status, headers, config) {
$rootScope.$broadcast("cm:myVisitsReceived", { data: data, status: status, success: false });
});
},
getTeamVisits: function () {
$http.get(cmSettings.apiUrl + '/api/v1/visits/team').success(function (data, status, headers, config) {
$rootScope.$broadcast("cm:teamVisitsReceived", { data: data, status: status, success: true });
})
.error(function (data, status, headers, config) {
$rootScope.$broadcast("cm:teamVisitsReceived", { data: data, status: status, success: false });
});
},
getVisit: function (visitNumber) {
$http.get(cmSettings.apiUrl + '/api/v1/visits/' + visitNumber).success(function (data, status, headers, config) {
$rootScope.$broadcast("cm:visitsReceived", { data: data, status: status, success: true });
})
.error(function (data, status, headers, config) {
$rootScope.$broadcast("cm:visitsReceived", { data: data, status: status, success: false });
});;
},
search: function (searchTerms) {
return $http.get(cmSettings.apiUrl + '/api/v1/visits/search/' + searchTerms).success(function (data, status, headers, config) {
$rootScope.$broadcast("cm:searchVisitsReceived", { data: data, status: status, success: true });
})
.error(function (data, status, headers, config) {
$rootScope.$broadcast("cm:searchVisitsReceived", { data: data, status: status, success: false });
});
},
};
}])
console output:
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
File: authorize
HTML1300: Navigation occurred.
File: login
HTML1200: microsoftonline.com is on the Internet Explorer Compatibility View List ('C:\Users\Micah\AppData\Local\Microsoft\Internet Explorer\IECompatData\iecompatdata.xml').
File: login
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
File: authorize
HTML1506: Unexpected token.
File: localhost:44300, Line: 115, Column: 1
The returned id_token is not parseable.
The returned id_token is not parseable.
State: 0edacc1d-a253-42ac-8a1d-cf1206ad3beb
State status:true
State is right
renewToken is called for resource:https://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Renew token Expected state: ca98c6f9-7a16-4744-828f-351cffedec9b|https://cloudmedIdentity.onmicrosoft.com/dataApi
Navigate url:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=ca98c6f9-7a16-4744-828f-351cffedec9b%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2
Navigate to:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=ca98c6f9-7a16-4744-828f-351cffedec9b%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2&prompt=none&login_hint=Test1%40cloudMedIdentity.onmicrosoft.com&domain_hint=cloudMedIdentity.onmicrosoft.com&nonce=220c7d60-d07a-449d-bbcf-dd4cd053365a
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
renewToken is called for resource:https://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Renew token Expected state: ca355b60-742a-48c2-8b8c-cd46a1b9b620|https://cloudmedIdentity.onmicrosoft.com/dataApi
Navigate url:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=ca355b60-742a-48c2-8b8c-cd46a1b9b620%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2
Navigate to:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=ca355b60-742a-48c2-8b8c-cd46a1b9b620%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2&prompt=none&login_hint=Test1%40cloudMedIdentity.onmicrosoft.com&domain_hint=cloudMedIdentity.onmicrosoft.com&nonce=c204e5c3-9d07-42e3-9787-2e340935ab8c
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
renewToken is called for resource:https://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Renew token Expected state: fdc47862-650b-411b-b59f-98cbf13b5715|https://cloudmedIdentity.onmicrosoft.com/dataApi
Navigate url:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=fdc47862-650b-411b-b59f-98cbf13b5715%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2
Navigate to:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=fdc47862-650b-411b-b59f-98cbf13b5715%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2&prompt=none&login_hint=Test1%40cloudMedIdentity.onmicrosoft.com&domain_hint=cloudMedIdentity.onmicrosoft.com&nonce=2f110029-8c7a-4584-aaae-b9a68284b3d9
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
renewToken is called for resource:https://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Renew token Expected state: 46dce352-c78b-453e-993d-7b43dbfee4c0|https://cloudmedIdentity.onmicrosoft.com/dataApi
Navigate url:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=46dce352-c78b-453e-993d-7b43dbfee4c0%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2
Navigate to:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=46dce352-c78b-453e-993d-7b43dbfee4c0%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2&prompt=none&login_hint=Test1%40cloudMedIdentity.onmicrosoft.com&domain_hint=cloudMedIdentity.onmicrosoft.com&nonce=ef3226f4-0c07-4dff-ad99-36dde840f7ee
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
renewToken is called for resource:https://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Renew token Expected state: e392c56e-5298-41cf-9f0b-4f0bed985b3d|https://cloudmedIdentity.onmicrosoft.com/dataApi
Navigate url:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=e392c56e-5298-41cf-9f0b-4f0bed985b3d%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2
Navigate to:https://login.microsoftonline.com/cloudMedIdentity.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=96408f66-4eab-4c44-8e59-eed93746bf8f&resource=https%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&redirect_uri=http%3A%2F%2Flocalhost%3A44300%2F&state=e392c56e-5298-41cf-9f0b-4f0bed985b3d%7Chttps%3A%2F%2FcloudmedIdentity.onmicrosoft.com%2FdataApi&nux=1&x-client-SKU=Js&x-client-Ver=1.0.2&prompt=none&login_hint=Test1%40cloudMedIdentity.onmicrosoft.com&domain_hint=cloudMedIdentity.onmicrosoft.com&nonce=c09911ac-c4ff-495f-b0a8-19931c82b902
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
State: ca98c6f9-7a16-4744-828f-351cffedec9b|https://cloudmedIdentity.onmicrosoft.com/dataApi
State status:true
State is right
Fragment has access token
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
LoadFrame: adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
Add adal frame to document:adalRenewFramehttps://cloudmedIdentity.onmicrosoft.com/dataApi
State: 46dce352-c78b-453e-993d-7b43dbfee4c0|https://cloudmedIdentity.onmicrosoft.com/dataApi
State status:true
State is right
Fragment has access token
You can set AzureAD:true to one of the routes that you want to protect. Adal will start the login and load this protected route after login finishes. When page displays, you can call webapi methods. You don't need loginSuccess event here.
Do you see loginSuccess event firing multiple times in your setup?
This issue was resolved by the ADAL js team: https://github.com/angular/angular.js/issues/1417

cannot use a different controller with a view with ui-router AngularJS

I'm using ui-router for routing my angular app. I have the following route:
'use strict';
//Setting up route
angular.module('admins').config(['$stateProvider',
function($stateProvider) {
// Admins state routing
$stateProvider.
state('admin_home', {
url: '/admin',
templateUrl: 'modules/admins/views/list-admins.client.view.html'
}).
state('adduser', {
url: '/admin/create',
templateUrl: 'modules/admins/views/create-admin.client.view.html',
}).
state('viewAdmin', {
url: '/admins/:adminId',
templateUrl: 'modules/admins/views/view-admin.client.view.html'
}).
state('editAdmin', {
url: '/admins/:adminId/edit',
templateUrl: 'modules/admins/views/edit-admin.client.view.html'
});
}
]);
This is within my 'Admin' module, and that has its own controller (AdminsController).
However, I want to be able to create a new user from here, and the controller to do that is called 'AuthenticationController' and is elsewhere in the structure.
As far as I know, I should be able to put something like:
state('adduser', {
url: '/admin/create',
templateUrl: 'modules/admins/views/create-admin.client.view.html',
controller:'AuthenticationController'
})
and it should work.
However - I keep getting redirected back to the index page.
I suspect this may be because I'm using HTML5 and have this in my config also:
// use HTML 5
$locationProvider.html5Mode(true).hashPrefix('!');
//Sets the HTTP header type for the redirects
$httpProvider.defaults.headers.common = {
'Accept': 'application/json',
'Content-Type': 'application/json'
Can anyone help?
You should add :
$urlRouterProvider.otherwise("/home");
And declare your controller inside your state function (not in your view files) like that :
state('viewAdmin', {
url: '/admins/:adminId',
controller : AdminsController,
templateUrl: 'modules/admins/views/view-admin.client.view.html'
})
If it doesn't work, try to remove :
$locationProvider.html5Mode(true).hashPrefix('!');
//Sets the HTTP header type for the redirects
$httpProvider.defaults.headers.common = {
'Accept': 'application/json',
'Content-Type': 'application/json'
Let me know ;)

Ionic controller not called after $state.go

I have a controller the get data from my back-end application when opening the state for the first time from the first controller it loads the data, but when it tries to open it again it does not load the new data
Here is how:
if (selectedServiceID == "000")
{
$state.go('balanceInquery');
};
Here is the called balanceInquery state controller:
.controller('BalanceInqueryController', function($scope, getAccountBalanceService, $state, $ionicLoading, $ionicPopup) {
getAccountBalanceService.get(username, pass, customerID, serviceAccID, langID)
.success(function(data) {
$scope.custBalance = data;
})
.error(function(data) {
var alertPopup = $ionicPopup.alert({
title: 'Error!',
template: 'Sorry something went wrong'
});
});
})
I had a similar problem. The first time was shown only after reload. The reason is view caching. Disable it with cache: false, like in my specific case:
$stateProvider
.state('login', {
url: '/login',
controller: 'LoginCtrl as vm',
templateUrl: 'app/login/login.html'
})
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html',
cache: false
})
This is due to view caching, which can be disabled in a variety of ways. See http://ionicframework.com/docs/nightly/api/directive/ionNavView/ for more details.

Categories

Resources