I have a problem, my page after login is not redirecting to main page. I have checked condition login working when I use $window.location. I want to use angular-route to prevent user without login to access my main menu. If I use $window.location, the user can access my main menu without login. Here is my js file
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'index.html'
})
.when('/mainmenu',{
resolve:{
"check":function($location,$rootScope){
if (!$rootScope.loggedIn) {
$location.path('/');
}
}
},
templateUrl:'content/mainmenu2.html'
})
.otherwise({
redirectTo:'/'
});
});
app.controller("logincont", ['$scope','$http','$window','$rootScope','$location',function($scope,$http,$window,$rootScope,$location){
$scope.login = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
if($scope.reslogin == null)
{
alert('Login Incorrect');
}
else
{
$rootScope.loggedIn = true;
$location.path('/mainmenu');
}
});
};
}]);
here is my html
<form>
<h1 class="tengah"> Form Login </h1>
<div class="form-group">
<label for="inputId">User Id</label>
<input type="text" class="form-control" ng-model="userid" placeholder="userid" required>
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" ng-model="pass" placeholder="Password" required>{{password}}
</div>
<button type="submit" class="btn btn-primary" ng-click="login()">
<span class="fa fa-sign-out"></span>Login</button>
</form>
You can do it by using a flag allowUnauth on the routes those you don't want to authenticate for e.g login and then change your routing like:-
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'index.html',
allowUnauth:true
})
.when('/mainmenu',{
templateUrl:'content/mainmenu2.html'
}).otherwise({
redirectTo:'/'
});
});
var unauthRoutes= [];
angular.forEach($route.routes, function(route, path) {
// push route onto unauthRoutes if it has a truthy allowUnauth value
route.allowUnauth && (unauthRoutes.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc)
{
var atuhRoute= (-1 === unauthRoutes.indexOf($location.path()));
if(atuhRoute && !$rootScope.loggedIn) {
$location.path('/');
}
});
Working plunker
Try something like
"use strict";
configureApp.$inject = ['$routeProvider'];
function configureApp($routeProvider) {
$routeProvider
.when('/mainmenu', {
resolve: {
ensureAthenticated: (function() {
ensureAthenticated.$inject = ['$rootScope'];
function ensureAthenticated($rootScope) {
if(!$rootScope.loggedIn) {
return Promise.reject('not athenticated');
}
else return Promise.resolve();
};
return ensureAthenticated;
}())
},
templateUrl:'content/mainmenu2.html'
})
.otherwise('/');
}
app.config(configureApp);
Related
I'm currently working on a project using Ionic v1. I have multiple user type in the project, wherein every user type must be redirected to a different page based on their time. I am unable to achieve this. Here is my code:
app.js:
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
.state('guest.home' , {
url: '/guesthome',
views: {
'guest-home': {
templateUrl: 'templates/guest-home.html',
controller: 'GuestCtrl'
}
}
})
.state('agent.home' , {
url: '/agenthome',
views: {
'agent-home': {
templateUrl: 'templates/agent-home.html',
controller: 'AgentCtrl'
}
}
})
controller.js:
.controller('LoginCtrl', function($scope, $state) {
$scope.userLogin = function(email, password) {
Backendless.UserService.login( $scope.email, $scope.password, true )
.then( $scope.userLoggedIn )
.catch ( $scope.gotError )
}
$scope.userLoggedIn = function( user ) {
console.log("User has logged in");
if ( user.user_type === "g" )
$state.go('guest.home');
else
$state.go('agent.home');
}
$scope.gotError = function( err ) {
console.log( "error message - " + err.message );
console.log( "error code - " + err.statusCode );
}
})
tabs-login.html:
<ion-content class="padding" ng-controller="LoginCtrl">
<div class="list">
<label class="item item-input item-floating-label">
<span class="input-label">Email</span>
<input type="text" placeholder="Email" ng-model="email">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Password</span>
<input type="password" placeholder="Password" ng-model="password">
</label>
</div>
<div class="text-center">
<button class="button button-positive" ng-click="userLogin()">
Login
</button>
</div>
</ion-content>
I'm getting the error error message - Could not resolve 'guest.home' from state 'tab.login' What am I doing wrong?
I believe the problem might be related to the fact that you use dots on your state names, without defining an abstract state to hold children.
Give it a shot without the dots ('guesthome' maybe?), or change your routing to have abstract states.
Here's an example:
$stateProvider
.state('setup', {
url: '/setup',
abstract: true,
templateUrl: 'js/views/setupView.html',
controller: 'SetupController'
})
.state('setup.bluetooth', {
url: '/bluetooth',
views: {
'setupContent': {
templateUrl: 'js/views/bluetoothSetupView.html',
controller: 'BluetoothSetupController'
}
}
})
.state('setup.truck', {
url: '/truck',
views: {
'setupContent': {
templateUrl: 'js/views/truckSetupView.html',
controller: 'TruckSetupController'
}
}
})
Hi all my requirement is to share input field data using get set method in factory with another controller.
angular.module('dataModule',[]).factory('myFact',function($http){
var user = {};
return {
getDetails: function () {
return user ;
},
setDetails : function (name,add,number) {
user.name = name;
user.add = add;
user.number = number;
}
}
});
Here is controller code.
angular.module('dataModule',[]).controller('thirdCtrl',function(myFact,$scope) {
$scope.saw=function(){
alert("hello get set method");
$scope.user=myFact.user.getDetails();
console.log(user);
};
});
Here is my html code
<div ng-controller="thirdCtrl">
<h1>hello gaurav come here after click one.</h1>
<div>
<lable>NAME</lable>
<div><input type="text"ng-model="user.name"></div>
</div>
<div>
<lable>ADDRESS</lable>
<div><input type="text"ng-model="user.add"></div>
</div>
<div>
<lable>MOBILE</lable>
<div><input type="number"ng-model="user.number"></div>
</div>
</br>
</br>
<button type="button" ng-click="saw()">Click</button>
</div>
Here is my app.js
var app = angular.module('sapient',['ui.router','dataModule']);
app.config(['$stateProvider','$urlRouterProvider',function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('one', {
url: '/one',
templateUrl: 'view/sap.html',
controller: 'sapCtrl'
})
.state('two', {
url: '/two',
templateUrl: 'view/two.html',
controller: 'secondCtrl'
})
.state('three', {
url: '/three',
templateUrl: 'view/three.html',
controller: 'thirdCtrl'
});
$urlRouterProvider.otherwise('two');
}])
Any Suggestions
Thanks in advance
The problem is you're recreating the module. Remove the [] (array of module dependencies) to make angular retrieve the previously created module, rather than create a new one.
Change:
angular.module('dataModule',[]).controller('thirdCtrl',function(myFact,$scope)
To:
angular.module('dataModule').controller('thirdCtrl',function(myFact,$scope)
This question already has an answer here:
AngularJS and Codeigniter - Combination & Data Transfer
(1 answer)
Closed 6 years ago.
I'm trying to use Angular.js and CodeIgniter together.
With ngRoute in my app, I'm setting in my main.js:
$locationProvider.html5Mode(true);
$routeProvider.when('/test', {
templateUrl: 'partials/test.html'
});
$routeProvider.otherwise({
templateUrl: 'partials/home.html'
});
In my routes.php, I'm setting:
$route['default_controller'] = 'home';
$route['(:any)'] = "home";
And in my home/index.php, I have the <ng-view></ng-view>.
The thing is, without the html5Mode(true) (with /#/ on the URL) everything works fine. But otherwise, the partials file works, but the page reloads anyway.
In Inspector Elements, things look like this:
partials/test.html loaded, but the page realoded, and the error "ngView: undefined" showed up.
I'm still learning Angularjs. Anyone can help?
this is a production form (i´m using htaccess)
in the js folder create a app.js
js/app.js
//create app module
var app = angular.module("app", []);
//login configuration
app.config(function($routeProvider){
$routeProvider.when("/login", {
controller : "loginController",
templateUrl : "templates/login.html"
})
.when("/home", {
controller : "homeController",
templateUrl : "templates/home.html"
})
});
js/controllers/controllers.js
//save & delete sessions
app.factory("sesionesControl", function(){
return {
//obtenemos una sesión //getter
get : function(key) {
return sessionStorage.getItem(key)
},
//creamos una sesión //setter
set : function(key, val) {
return sessionStorage.setItem(key, val)
},
//limpiamos una sesión
unset : function(key) {
return sessionStorage.removeItem(key)
}
}
})
//simple message in bad login
app.factory("mensajesFlash", function($rootScope){
return {
show : function(message){
$rootScope.flash = message;
},
clear : function(){
$rootScope.flash = "";
}
}
});
//angular login & logout
app.factory("authUsers", function($http, $location, sesionesControl, mensajesFlash){
var cacheSession = function(email){
sesionesControl.set("userLogin", true);
sesionesControl.set("email", email);
}
var unCacheSession = function(){
sesionesControl.unset("userLogin");
sesionesControl.unset("email");
}
return {
//return authUsers
login : function(user){
return $http({
url: 'http://localhost/login_ci_angularjs/login/loginUser',
method: "POST",
data : "email="+user.email+"&password="+user.password,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
if(data.respuesta == "success"){
//if true clear flash messages
mensajesFlash.clear();
//create session with email
cacheSession(user.email);
//redirect to home
$location.path("/home");
}else if(data.respuesta == "incomplete_form"){
mensajesFlash.show("The email & user are required");
}else if(data.respuesta == "failed"){
mensajesFlash.show("The email ore password are wrong");
}
}).error(function(){
$location.path("/")
})
},
//close session
logout : function(){
return $http({
url : "http://localhost/login_ci_angularjs/login/logoutUser"
}).success(function(){
//delete session in sessionStorage
unCacheSession();
$location.path("/login");
});
}
}
})
app.controller("homeController", function($scope, sesionesControl, authUsers){
$scope.email = sesionesControl.get("email");
$scope.logout = function(){
authUsers.logout();
}
})
//permisos
app.run(function($rootScope, $location, authUsers){
//url that the user can access
var rutasPrivadas = ["/home","/info","/login"];
$rootScope.$on('$routeChangeStart', function(){
if(in_array($location.path(),rutasPrivadas) && !authUsers.isLoggedIn()){
$location.path("/login");
}
//if user go to login (if the session exist redirect to home)
if(($location.path() === '/login') && authUsers.isLoggedIn()){
$location.path("/home");
}
})
})
//controller loginController
app.controller("loginController", function($scope, $location, authUsers){
$scope.user = { email : "", password : "" }
authUsers.flash = "";
//submit form
$scope.login = function(){
authUsers.login($scope.user);
}
})
//if user has permissions in the url
function in_array(needle, haystack, argStrict){
var key = '',
strict = !! argStrict;
if(strict){
for(key in haystack){
if(haystack[key] === needle){
return true;
}
}
}else{
for(key in haystack){
if(haystack[key] == needle){
return true;
}
}
}
return false;
}
templates/login.htm
<form name="loginUserForm">
<fieldset>
<legend>form login</legend>
<div class="row">
<div ng-show="flash">
<div data-alert class="alert-box alert round">{{ flash }}</div>
</div>
<div class="large-12 columns">
<label>Email</label>
<input type="email" required placeholder="mail#mail.com" ng-model="user.email">
</div>
<div class="large-12 columns">
<label>Password</label>
<input type="password" required placeholder="Password" ng-model="user.password">
</div>
<button type="submit" ng-disabled="!loginUserForm.$valid" ng-click="login(user)" class="button expand round">Login</button>
</div>
</fieldset>
</form>
Login.php controller
class Login extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->view("login");
}
//called from angular controller.js
public function loginUser(){
if($this->input->post("email") && $this->input->post("password"))
{
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
if($this->form_validation->run() == false){
echo json_encode(array("respuesta" => "incomplete_form"));
}else{
$this->load->model("login_model");
$email = $this->input->post("email");
$password = $this->input->post("password");
$loginUser = $this->login_model->loginUser($email,$password);
if($loginUser === true){
echo json_encode(array("respuesta" => "success"));
}else{
echo json_encode(array("respuesta" => "failed"));
}
}
}else{
echo json_encode(array("respuesta" => "incomplete_form"));
}
}
public function logoutUser(){
$this->session->sess_destroy();
}
}
apllications/views/login.php
<!DOCTYPE html>
<html lang="es" ng-app="app">
<head>
<meta charset="UTF-8" />
<title>CI & Angular</title>
</head>
<body>
<!-- with this ng-view, we load all views -->
<div class="row" ng-view></div>
<script type="text/javascript" src="<?php echo base_url() ?>js/angular.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>js/app.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>js/controllers/controllers.js"></script>
</body>
</html>
templates/home.html
<h3 class="subheader">Hello {{ email }}</h3>
<button ng-click="logout()" class="large-12 button expand">Logout</button>
This issue has been posted a few times but I cannot seem to find the error within my code. Can somebody help spot the issue in my code?
Below is my app.js file
'use strict';
/**
*jslint node:true
* #ngdoc overview
* #name impApp
* #description
* # impApp
*
* Main module of the application.
*/
/*global Firebase, angular*/
angular
.module('impApp', [
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase'
])
.config(function ($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/', {
templateUrl: 'views/login.html',
controller: 'AuthCtrl',
controllerAs: 'auth'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Secondly, this is my controller contents on "auth.js":
'use strict';
/*global Firebase, angular, console*/
angular.module('impApp')
// Re-usable factory that generates the $firebaseAuth instance
.factory("Auth", function ($firebaseAuth) {
var ref = new Firebase("https://impl.firebaseio.com");
return $firebaseAuth(ref);
})
.controller('AuthCtrl', function ($scope, $http, Auth) {
// Listens for changes in authentication state
Auth.$onAuth(function (authData) {
$scope.authData = authData;
});
// Logs in a user with email & password
$scope.login = function () {
Auth.authWithPassword({
email : $scope.email,
password : $scope.password
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
};
// Logs out the logged-in user
$scope.logout = function () {
Auth.$unauth();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Finally, I have outlined the "login.html" contents:
<div>
<form class="form-signin">
<h2 class="form-signin-heading">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
<p></p>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Thank you Pierre-Alexandre. Adding the link to the js file in the index.html resolved this issue.
My app has a login form consisting of a username, password, and a button to click to log in. However, for some reason I just can't get ui-keypress to work on the login button. I'm using ui-bootstrap and ui-utils. ui-utils has the keypress directive included.
Here's what I have so far:
My login partial:
<div id="loginForm">
<img id="logo" src="img/login_logo.png"/>
<alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">
{{alert.msg}}
</alert>
<input type="text" id="username" ng-model="username" placeholder="Username"/>
<input type="password" id="password" ng-model="password" placeholder="Password"/>
<button type="button" id="loginBtn" class="btn btn-primary" ng-model="loginModel" ng-click="login()" ui-keypress="{13:'keypressLogin($event)'}">
Login
</button>
</div>
My login controller:
ClutchControllers.controller("LoginController", [
'$scope',
'$http',
'$location',
'$cookieStore',
'Auth',
function($scope, $http, $location, $cookieStore, Auth) {
// Redirect if already logged in
if(Auth.isLoggedIn()) {
$location.path('/dashboard');
}
$scope.alerts = [];
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
}
$scope.login = function() {
Auth.login({
username: $scope.username,
password: $scope.password
}, function(err, user) {
if(err) {
console.log(err);
$scope.alerts = [err];
} else {
console.log(user);
console.log(Auth.isLoggedIn());
//this this if you want to change the URL and add it to the history stack
$location.path('/dashboard');
}
});
}
$scope.keypressLogin = function($event) {
console.log($event);
console.log($scope.username);
}
}
]);
And finally, my app routing:
angular.module('myApp', [
'ngCookies',
'ui.utils',
'ui.bootstrap',
'ui.utils',
'clutch.services',
'clutch.controllers'
])
.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider
.when('/login', {
controller: "LoginController",
templateUrl: "partials/login.html",
auth: false
})
.when('/dashboard', {
controller: "DashboardController",
templateUrl: "partials/dashboard.html",
auth: true
})
.otherwise({ redirect: "/login" });
}]);
ClutchControllers = angular.module('clutch.controllers', ['ui.bootstrap']);
ClutchServices = angular.module('clutch.services', ['ngResource']);
Just a thought, why would you want to use ui-keypress. IMHO using a form is better solution in this case. Consider this...
<form ng-submit="login()">
<input type="text"/>
<input type="password"/>
<button type="submit">Login</button>
</form>
Taking a wild guess -- you've got the ui-keypress attribute on your button and not your two input tags..
Took me a bit to reproduce in jsfiddle w/ all your dependencies: http://jsfiddle.net/tuv45/