This is my app.js
var Myapp = ons.bootstrap('Myapp',[]);
document.addEventListener('deviceready', function () {
}, false)
controller.js :
Myapp.controller('LoginCtrl', ['$scope', '$state', 'LoginSrvs', function ($scope, $state, LoginSrvs)
{
$scope.login = function (LoginAccount) {
debugger;
var username = LoginAccount.username;
var password = LoginAccount.password;
var parameter = JSON.stringify({ username: username, password: password });
var loginData = LoginSrvs.login(parameter);
loginData.then(function (str) {
})
$state.go('index');
};
}]);
and my route .js
MyApp.config(
['$stateProvider',
'$urlRouterProvider',
function ($stateProvider,
$urlRouterProvider) {
debugger;
$stateProvider
.state('index', {
url: '/index',
templateUrl: ''
})
$urlRouterProvider.otherwise('/');
}]);
state.go not found and not trigger the controller action on click.
if you don't want any content then replace templateUrl: '' with template: ''.
Related
I tired to follow this tutorial
app.config(['$stateProvider', '$urlRouterProvider', '$compileProvider',
function ($stateProvider, $urlRouterProvider, $compileProvider) {
self = this;
$compileProvider.preAssignBindingsEnabled(true);
$urlRouterProvider.otherwise('/');
$stateProvider.state('home', {
url: '/',
//template: '<home-component></home-component>',
component: 'homeComponent',
params: {
selectedFilter: undefined
},
resolve: {
isAdOps: function () {
return false;
}
}
})
and
(function (app) {
app.component('homeComponent', {
templateUrl: 'partials/home-partial.html',
bindings: {
isAdOps: '<'
},
controller: ['$scope', '$state', function ($scope, $state) {
var self = this;
console.log("self.isAdOps = " + self.isAdOps);
self.isFullList = false;
// this.$onChanges = function (isAdOps) {
// if (angular.isDefined(isAdOps)) {
//
// self.isAdOps = isAdOps;
// console.log("self.isAdOps = " + self.isAdOps);
// $scope.isAdOps = !self.isAdOps ? true : self.isAdOps;
//
// }
// };
self.addVoice = function () {
$state.go("add");
};
$scope.$broadcast('searchNoFilter');
}]
});
})
(promptoWeb);
but still i get to the console: self.isAdOps = undefined
what is missing?
injection into the controller didn't work as well:
angular 1.5 passes undefined value to a controler after state.Provider "resolve"
When you resolve something, you can inject it. It is not added to controller as property automatically:
controller: ['$scope', '$state', 'isAdOps', function ($scope, $state, isAdOps) {
var self = this;
self.isAdOps = isAdOps;
console.log("self.isAdOps = " + self.isAdOps);
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)
I am using UI Router Tabs for navigation/routing. There are three tabs [User, Address and Service]. Individual tab have their own state, url, controller and template.
How can I pass request params (saved object ID, firstname and lastname) from User tab [UserCtrl.js] to AddressCtrl.js and ServiceCtrl.js.
HOW CAN I ACHIEVE THIS?
What I have done so far?
app.js
'use strict';
var app = angular.module('xyzApp', [ 'ui.router','ngResource', 'ui.bootstrap', 'ui.router.tabs']);
app
.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', '$interpolateProvider', '$locationProvider',
function($stateProvider, $urlRouterProvider, $httpProvider, $interpolateProvider, $locationProvider) {
// CSRF Support
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$urlRouterProvider.otherwise('/');
$stateProvider
.state('new', {
url: '/',
controller: 'MainCtrl',
templateUrl: 'partials/base.html'
})
.state('new.user', {
url: '/new/user',
controller: 'UserCtrl',
templateUrl: 'partials/user-tab.html'
})
.state('new.address', {
url: '/new/address',
controller: 'AddressCtrl',
templateUrl: 'partials/address-tab.html'
})
.state('new.service', {
url: '/new/service',
controller: 'ServiceCtrl',
templateUrl: 'partials/service-tab.html',
})
}]);
MainCtrl.js
'use strict';
app
.controller('MainCtrl', ['$scope', function($scope) {
// Inititalise the new personnel page tabs
$scope.initialise = function() {
$scope.go = function(state) {
$state.go(state);
};
$scope.personneltabinfo = [
{
heading: 'User',
route: 'new.user',
//params: {
// userId: $scope.userId
//},
},
{
heading: 'Address',
route: 'new.address',
},
{
heading: 'Service',
route: 'new.service'
}
];
};
$scope.initialise();
}]);
UserCtrl.js
'use strict';
app
.controller('UserCtrl', ['$scope', '$rootScope', '$http', '$compile', '$timeout', 'userServices',
function($scope, $rootScope, $http, $compile, $timeout, userServices) {
$scope.userId = '';
$scope.savePerson = function() {
console.log("This is userData:" + $scope.userData);
// user resource service
userServices.addUser($scope.userData)
.then(function(data) {
// pass $scope.userId to [Account and Service] routes view.
// pass firstname and secondname value to [Account and Service] routes view so it’s value can be shown on their panel-title.
$scope.userId = data.id;
toastr.success('Personnel ' + $scope.baseData.first_name + ' record saved into database');
}, function(data, status, headers, config) {
toastr.error('Field Error:' + " Please fill all fields mark with * ");
});
};
}]);
I'm angular beginner!
If I understand your question, you want to pass the data from a controller to another controller.
You can check on: Passing data between controllers in Angular JS?
You can use :
a service: https://docs.angularjs.org/guide/services,
$rootScope but that's not the best solution,
or the binding data between components: https://docs.angularjs.org/guide/component
How to redirect to Home Page after Login successful,
I am using UI-router and below is my ui-router code.
var myrouting=angular.module('routingDemoApp', ['ui.router'])
myrouting.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("", "/index")
$stateProvider
.state('index', {
url: "/index",
templateUrl: "../Views/home.html"
})
.state('contactus', {
url: "/contactus",
templateUrl: "../Views/contactus.html",
})
.state('home', {
url: "/home",
templateUrl: "../Views/home.html",
})
.state('myModal', {
url: "/myModal",
templateUrl: "../Views/SignInPage.html",
})
}]);
I have a button element calling ng-click='login function' for validation Username and Password. once credentials are valid i want to redirect a page to "Home.html"
How to call ui-route after successfully login in below function?
var mymodule2 = angular.module('module2', []);
mymodule2.controller('controller2', function ($scope) {
$scope.loginFunction = function () {
alert("Login");
if ($scope.username == 'abcd' && $scope.password == 'hello123') {
console.log('Login sucessfull');
***// Redirect to Home Page.***
}
}
});
You can just use $state.go("home"); like this, where the "home" is the state name where you would like to go:
var mymodule2 = angular.module('module2', []);
mymodule2.controller('controller2', function ($scope, $state) {
$scope.loginFunction = function () {
alert("Login");
if ($scope.username == 'abcd' && $scope.password == 'hello123') {
console.log('Login sucessfull');
$state.go("home");
}
}
});
Use `$state.go("home");
var mymodule2 = angular.module('module2', []);
mymodule2.controller('controller2', function ($scope) {
$scope.loginFunction = function () {
alert("Login");
if ($scope.username == 'abcd' && $scope.password == 'hello123') {
console.log('Login sucessfull');
// add $state.go here
$state.go("home);
}
}
});
I'm having a issue in my Angular app with regards to the resolve section of the ui-router. I'm trying to present a login modal the first time a user hits the website.
In my app.config.js, how do I inject my 'loginService':
angular
.module('rage')
.config(config);
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/dashboard");
$stateProvider
.state('main', {
url: "/dashboard",
templateUrl: "app/views/dashboard.html",
controller: 'MainCtrl',
data: { pageTitle: 'RAGE', requireLogin: true },
resolve: {
// *** WHERE DO I INJECT 'loginService' ? ***
authUser: function () {
return loginService.loginModal().then(function (user) {
$rootScope.userID = user.userId;
userService.openUserSession(razorEnvJson).then(function (data) {
// assign some scope vars here..
});
})
}
}
})
.state('login', {
url: "/login",
templateUrl: "app/views/login-view.html",
controller: 'LoginCtrl'
})
}
loginService code:
(function () {
'use strict';
angular.module('rage').service('loginService',
['$rootScope', '$modal', 'datacontext', 'userService', login]);
function login($rootScope, $modal, datacontext, userService) {
var modalInstance = null
this.loginModal = function(){
modalInstance = $modal.open({
animation: true,
templateUrl: 'app/components/login/login.html',
controller: 'LoginCtrl as login',
});
return modalInstance.result.then(function (user) {
return user;
});
};
}
})();
LoginCtrl controller code:
(function () {
'use strict';
angular.module('rage').controller('LoginCtrl',
['$rootScope', '$scope', '$modalInstance', '$q', 'datacontext', 'userService', authenticate]);
function authenticate($rootScope, $scope, $modalInstance, $q, datacontext, userService) {
var login = this;
// OK,CANCEL CLICK EVENTS FROM MODAL !!!
$scope.ok = function () {
// var user = userService.authenticateWebUser(); // **** TBD ****
var user = {userId: login.userId, pswd: login.pswd};
$modalInstance.close(user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
})();
I've also attempted $rootScope.$on('$stateChangeStart' event inside app.js to transition the state from main to login, but that hangs up on me.
**** MY UPDATED APP.CONFIG.JS CODE, SEPT 18 ****
Here is the proper usage of resolve: using ui-router states.
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/dashboard");
$stateProvider
.state('main', {
url: "/dashboard",
templateUrl: "app/views/dashboard.html",
controller: 'MainCtrl',
data: { pageTitle: 'RAGE', requireLogin: true },
resolve: {
authUser: ['$rootScope', 'loginService', 'userService', function ($rootScope, loginService, userService) {
return loginService.loginModal().then(function (user) {
$rootScope.userID = user.userId;
initSession(user, $rootScope, loginService, userService);
})
}]
}
})
.state('login', {
url: "/login",
templateUrl: "app/views/login-view.html",
controller: 'LoginCtrl'
})
}
function initSession(user, $rootScope, loginService, userService) {
userService.getInitParams().then(function (envJson) {
// some code omitted here...
userService.openUserSession(envJson).then(function (data) {
var sessionID = data.data[0];
$rootScope.rageSessionVars.sessionID = sessionID;
$rootScope.rageSessionVars.userID = $rootScope.userID; // *** HOW TO SUSPEND ALL CODE UNTIL userID IS ASSIGNED ??? ***
console.log("sessionID = " + sessionID);
$rootScope.rageSessionVars.currDashboardName = "Default";
});
});
}
* MainCtrl controller code *
(function () {
'use strict';
angular.module('rage')
.controller('MainCtrl',
['$rootScope', '$scope', '$interval', '$window', '$state', '$location', 'widgetDefinitions',
'defaultWidgets', 'gadgetInitService', main]);
function main($rootScope, $scope, $interval, $window, $state, $location, widgetDefinitions, defaultWidgets, gadgetInitService, authUser) {
var main = this;
**** authUser IS NEVER DEFINED !!!
if ($scope.userID == undefined) { /// *** NOTHING WORKS HERE !!! ***
//$state.go('login');
//$location.url('index.html#/?login');
//return ;
}
if ($scope.userID == undefined) {
main.userName = "risk user";
}
else {
$scope.main.userName = $scope.userID;
}
}
})();
Edit:
I see your getting confused on the use of 'Resolve'.
It should be used when you want some data passed into the controller when it's being run. Not to run a function before initiating a controller.
This isn't what you really want in this situation.
It kinda depends on your authentication method, cookies/tokens etc.
Here is a similar method that I would follow.
Have a Login service which handles the following
-- Login/Logout of the user
-- Checks if the user is authenticated
In your Controller call your service to check if the user is logged in.
-- If the user is not logged in, then prompt login screen
-- If the user is logged in, then let the controller continue execution
How I handle it, is whenever the user makes an UnAuthorised request where the server returns a 401 response I call my LoginService to prompt the login screen again.
I use an authInterceptor in Angular to catch any 401 response from the server.
Here is a nice guide on it: http://onehungrymind.com/winning-http-interceptors-angularjs/
This allows you to write your Unauthorized handler in one place.
Hope that makes it a bit clearer.