My project use angularJS 1.6.2
the problem is that user info is correct, but doesn't change page through $state.go(sidebar.overall);
But it chage page with twice login, and the second login with refresh page.
The first login is success with server,and has got the success response.
my login.js as following:
if($scope.loginForm.$valid) {
var postData = {
username : $scope.username,
password : $scope.loginForm.password.$modelValue,
smsCode : $scope.messageCode
};
$scope.method = "post";
$scope.url = BASE_URL + "/user/login/users";
$http({
method:$scope.method,
url: $scope.url,
data : postData,
headers : {
"Content-Type": 'application/json'
}
}).then( function (response, event) {
console.log(response);
event.preventDefault();
$state.go("sidebar.overall");
if(response.data.success == true){
$cookieStore.put("userMessage", response);
$state.go("sidebar.overall");
if($cookieStore.get('userMessage')){
$scope.uMessage = $cookieStore.get('userMessage');
$http({
method: 'GET',
url: BASE_URL + '/user/roles/privileges/parts/' + $scope.uMessage.data.data.user.roleId,
headers : {
"Content-Type": 'application/json'
}
}).then(function (res){
localStorage.setItem('permitInfo',JSON.stringify(res.data));
}, function(res){
console.log(res);
});
}
}
and app.js file :
.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function ($stateProvider, $urlRouterProvider, $httpProvider){
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
$urlRouterProvider.otherwise( function($injector, $location) {
var $state = $injector.get("$state");
$state.go("loginlogout");
});
}]).controller('RootController', ['$rootScope', '$scope', $timeout','$location', '$state', '$cookieStore', 'locals', function($rootScope, $scope, $timeout, $location, $state, $cookieStore, locals){
if($cookieStore.get('userMessage')){
$rootScope.userMessage = $cookieStore.get('userMessage');
console.log($rootScope.userMessage);
} else {
$state.go('loginlogout');
}
$rootScope.permitInfo = JSON.parse(localStorage.getItem('permitInfo'));
$scope.$on('$locationChangeStart',function(evt, next, previous) {
angular.element('#loading').modal('show');
});
$scope.$on('$locationChangeSuccess',function(evt, next, previous) {
angular.element('#loading').modal('hide');
angular.element(".modal").modal("hide");
});
$scope.$on('$stateChangeSuccess',function(evt, next, previous) {
angular.element('#loading').modal('hide');
angular.element(".modal").modal("hide");
});
$scope.$on('$viewContentLoaded',function(evt, next, previous) {
angular.element('input').attr("autocomplete", "off");
window.scrollTo(0,0);
angular.element(".modal-backdrop").hide();
});
angular.module('frontierApp.loginlogout', ['ui.router', 'ngCookies'])
.config(['$stateProvider', function($stateProvider){
$stateProvider
.state('loginlogout',{
url : '/login',
templateUrl: 'modules/loginlogout/login_view.html',
controller: 'LoginController'
})
}])
thanks for help.
Related
I am very new to Angular and was trying to use it on my Rails Application. But I got the following error.
TypeError: Cannot read property 'index' of undefined
app.js code
angular.module('ticket', ['ngResource', 'ui.router', 'templates'])
.controller('AppCtrl', ['$rootScope', function($rootScope) {
var _this = this;
return $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
return $rootScope.pageTitle = $route.current.title;
});
}])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl'
})
.state('members', {
url: '/members',
templateUrl: 'members/_members.html',
controller: 'MemberCtrl'
})
.state('guards', {
url: '/guards',
templateUrl: 'guards/_guards.html',
controller: 'GuardCtrl'
})
.state('tickets', {
url: '/tickets',
templateUrl: 'tickets/_tickets.html',
controller: 'TicketCtrl'
});
$urlRouterProvider.otherwise('home')
}]);
memberCtrl.js code (inside members directory)
angular.module('ticket')
.factory('Member', ['$resource', function($resource) {
return $resource("/members/:id", {id: "#id"}, {
get: { method: 'GET'},
save: { method: 'POST'},
index: { method: 'GET', isArray: true},
remove: { method: 'DELETE'},
"delete": { method: 'DELETE'},
update: { method: 'PUT'}
});
}])
.controller('MemberCtrl', ['$scope', function($scope, Member) {
console.log(Member.index());
$scope.members = Member.index();
}]);
You need to inject dependency Member in the controller properly.
.controller('MemberCtrl', ['$scope', 'Member', function($scope, Member) {
//^^^^^^^^^^
instead of
.controller('MemberCtrl', ['$scope', function($scope, Member) {
angular.module('myApp',[])
.controller('loginCtrl',function ($scope, $http, $rootScope, $location, $window{
$scope.login = function(loginData){
$scope.dataLoading = true;
$scope.loginData = angular.copy(loginData);
$http({
method : 'GET',
url : 'php/login.php',
params: {'email' : loginData.email,'password': loginData.password,'rand' : Math.random()}
}).then(function mySucces(response,$location){
$scope.dataLoading = false;
$scope.msg1 = response.data.msg1;
$scope.msg2 = response.data.msg2;
$scope.firstname = response.data.firstname;
$scope.flag = response.data.flag;
console.log($scope.flag);
$location.url('http://localhost/timetrake/welcome.html');
}, function myError(response) {
$scope.user = response.statusText;
});
}
});
You can use Angular $window:
$window.location.href = 'timetrake/welcome.html';
Then
$scope.dataLoading = true;
$scope.loginData = angular.copy(loginData);
$http({
method : 'GET',
url : 'php/login.php',
params: {'email' : loginData.email,'password': loginData.password,'rand' : Math.random()}
}).then(function mySucces(response,$location){
$scope.dataLoading = false;
$scope.msg1 = response.data.msg1;
$scope.msg2 = response.data.msg2;
$scope.firstname = response.data.firstname;
$scope.flag = response.data.flag;
console.log($scope.flag);
$window.location.href = 'timetrake/welcome.html';);
}, function myError(response) {
$scope.user = response.statusText;
});
$location.path('/timetrake/welcome.html');
Why dont you add welcome.html into a scope route config and so u can do '/timetrake/welcome'
Inject $location in your controller
For example
jimApp.controller('mainCtrl', function($scope, $location){
$location.url(".....")
});
Try this
$location.path('/timetrake/welcome.html');
I prefer you to use ng-route it gives you more flexibility and it maintain state for redirection and it can easily navigate by just
$state.go()
How can I prevent user enter App url's if he doesn't logged.
App.js:
var MTApp = angular.module('MTApp', ['MEControllers','ui.router','services']);
MTApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'login.html'})
.state('login-app', {
url : '/Login',
templateUrl : 'login.html'})
.state('input-parameters', {
url : '/Parameters',
templateUrl : 'parameters.html'});
})
main.js:
var MEControllers = angular.module('MEControllers',[]);
MEControllers.controller('LoginAppCtrl', LoginAppCtrl);
MEControllers.controller('RequestCtrl', RequestCtrl);
function LoginAppCtrl($scope, $http,utilities,$location,$rootScope) {
var self = this;
self.request = {
user: '',
password:''
}
self.postprocess = function(){
//self.request.values = self.request.values.split(",");
}
self.submitRequest = function(){
self.postprocess();
console.log(self.request);
$http({
method : 'POST',
url : url,
headers: {'Content-Type': 'application/json'},
data : self.request
}).success(function(data, status, headers, config) {
if (data.status) {
// successfull login
// User.isLogged = true;
// User.username = data.user;
// $rootScope.loggedInUser = $scope.user;
$location.path("/Parameters");
}
else {
// User.isLogged = false;
//User.username = '';
}
}).error(function(data, status, headers, config) {
alert('Invalid Login Details');
});
}
this.validate = function(){
console.log(self.request);
}
}
function RequestCtrl($scope, $http,utilities,$location) {
var self = this;
self.request = {
}
self.postprocess = function(){
}
self.submitRequest = function(){
self.postprocess();
console.log(self.request);
$http({
method : 'POST',
url : url,
headers: {'Content-Type': 'application/json'},
data : self.request
}).success(function(data, status, headers, config) {
utilities.setOutput(data);
console.log(data);
}).error(function(data, status, headers, config) {
alert('Error!');
});
}
this.validate = function(){
console.log(self.request);
}
}
How can I get indocation if user log-in?
Moreover How can I prevent user to enter pages through url, how can I hide the url?
You could make a local storage objectwith auth details and check when the user starts the app like this:
if(window.localStorage.auth) {
$urlRouterProvider.otherwise('/tab/index');
}else{
$urlRouterProvider.otherwise('/login');
}
and in your main controller something like :
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
if(window.localStorage.auth) {
$state.go(toState.name)
}else{
$urlRouterProvider.otherwise('/login');
}
})
which should check when the route changes.
You can do it with the help of $rootscope service.On every routeChange Start Check that if user is login or not(you can create service to check) and if user is logged in redirect to desired page otherwise redirect it on login page.
Here is the required code
app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);
.factory('Auth', function(){
var user;
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
})
Ps:- Sorry for bad english.
Source
I would like to change the route of an angularjs application build with ionic framework, but the route didn't change
this is my code of app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.state('app.annuaire.menuitempage', {
url: "/menuitempage/:ID",
views: {
'menuContent' :{
templateUrl: "templates/menuItemPage.html",
controller: function($stateParams){
$stateParams.ID ;
}
}
}
})
.state('app.annuaire', {
url: "/annuaire",
views: {
'menuContent' :{
templateUrl: "templates/annuaire.html",
controller: 'MenuItemCtrl'
}
}
})
And this is the code of my controller
angular.module('starter.controllers', [])
.controller('MenuItemCtrl', function($scope, $http, $location) {
$scope.itemsMenu = {};
var responsePromise = $http.get("http://monguidepratique.com/mobile/getCategories.php?parent_id=0");
responsePromise.success(function(data, status, headers, config) {
//alert(data);
$scope.itemsMenu = data;
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
$scope.itemClick = function(path){
alert(1);
$location.path(path);
};
})
And this is my html code in annuaire.html
<div class="col" ng-click="itemClick('/menuitempage/1628')"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>
Try
$location.path(path)
instead of
$state.go(path)
You need to inject $location service into your controller.
Edit
If you are using $state.go - you should to use it next way:
$scope.itemClick = function(id){
$state.go('app.annuaire.menuitempage', {'ID': id})
};
And HTML:
<div class="col" ng-click="itemClick(1628)"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>
The first param is state name, not URL, the second is an Object with your params.
I solved my problem
in annuaire.html i changed
itemClick('/menuitempage/1628')
by
itemClick('/app/menuitempage/1628')
and i changed the route name app.annuaire.menuitempage by
app.menuitempage
.state('app.menuitempage', {
url: "/menuitempage/:ID",
views: {
'menuContent' :{
templateUrl: "templates/menuitempage.html",
controller: 'SubMenuCtrl'
}
}
})
Is it possible to use a scope in a factory then using it on multiple controllers ?
I'm not really up to writing the same code in every controller, it'll be a pain to work on it ^^
Here's my current idea.
.factory('FactoryName', function($scope, $routeParams, $http) {
return {
search : function(str, http) {
var url = str+'.json';
return $http.get(url).success(http).error(function() {
alert('Unable to get back the data');
});
}
httpSuccessPaper : function(response) {
$scope.papers = response;
}
This way I only have this code once and all my controller are able to use the json of "reference". I could also write something like ng-repeat="p in papers" in some view.
Here is the way I call it in my controller :
.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {
FactoryName.search("Paper",FactoryName.httpSuccessPaper).then(function(){
$scope.paper = getByIdPa($scope.papers,$routeParams.id);
})
It seems a bit strange to me and I'm almost sure I'm trying something impossible.
I would like your opinion.
Thank you !
you can do it like this:
angular.module('apiServices', ['ngResource'])
.factory('ExampleService', ['$http', 'serviceUrl', function ($http, serviceUrl) {
return{
getInteractions: function () {
return $http({method: 'GET', url: serviceUrl + 'ctest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
},
getRoots: function () {
return $http({method: 'GET', url: serviceUrl + 'ntest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
},
getLogging: function (params) {
return $http.post(serviceUrl + 'atest', params);
},
getMessage: function (params) {
return $http({method: 'GET', url: serviceUrl + 'btest', params: params, headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
}
};
}]);
You don't want Services dealing with scopes. It's ok to repeat just the setting the scope part.
.factory('FactoryName', function($scope, $routeParams, $http) {
return {
search : function(str) {
var url = str+'.json';
return $http.get(url)
}
Then the controller:
.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {
FactoryName.search("Paper").then(function(papers){
$scope.paper = getByIdPa($papers,$routeParams.id);
})