Sometimes ng-click don't work in Ionic - javascript

I'm new IONIC & AngularJS. Currently, working on an app & stuck at a point. Don't how to resolve the issue.
I've a login form. After user login to the app, he/she will land at HOME page. In the home page, I've an image. On that image, i'm using ng-click. So, on click of that image, it'll redirect the user to some other page. Here I'm facing the issue & the issue is just after login when I'm coming to the home page, on click of that image ng-click is not working at all. But, once I refresh the browser & click on that image ng-click start working. Don't know why this wired thing is happening.
Here are all files which I'm using. The ionic version which I'm using in 1.7.12
app.js
(function(){
var app = angular.module('e2pro', ['ionic', 'e2pro.LoginController', 'e2pro.HomeController', 'e2pro.AttendanceController', 'e2pro.LogoutController','e2pro.MenuController','e2pro.EmpProfileController','e2pro.EmpSearchController', 'e2pro.VendorController', 'ngMessages', 'ngCordova', 'angularMoment']);
var requestToken = "";
var accessToken = "";
var deviceToken = null;
var access_token = null;
var refresh_token = null;
var session_id = null;
var user_id = null;
var user_login_type = null;
var route_to = null;
app.run(function($ionicPlatform, RequestsService, GeoAlert) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
console.log('inside app.run function');
});
});
// Service for logout user from app
app.factory("User", function($http, $q, $rootScope, $ionicHistory, $state) {
return {
logout: function(){
window.localStorage.clear();
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
$ionicHistory.nextViewOptions({ disableBack: true, historyRoot: true });
$state.go("login");
}
}
});
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'MenuController'
})
.state('app.tabs', {
url: "/tabs",
views: {
'menuContent': {
templateUrl: "templates/tabs.html",
}
}
})
.state('login', {
url: "/login",
templateUrl: "templates/login.html",
//controller: 'LoginController'
})
.state('markEmpAttendance', {
url: "/markEmpAttendance",
templateUrl: "templates/attendance/markEmpAttendance.html",
//controller: 'AttendanceController'
})
.state('app.tabs.home', {
url: '/home',
views: {
'home-tab': {
templateUrl: 'templates/home.html',
}
}
})
.state('app.tabs.emp-profile', {
url: '/emp-profile/:empId',
views: {
'home-tab': {
templateUrl: 'templates/empProfile.html',
//controller: 'EmpProfileController'
}
}
})
.state('app.tabs.vendor', {
url: '/vendor',
views: {
'home-tab': {
templateUrl: 'templates/vendor/vendor.html',
//controller: 'EmpProfileController'
}
}
})
.state('app.tabs.emp-search', {
url: '/emp-search',
views: {
'home-tab': {
templateUrl: 'templates/empSearch.html',
//controller: 'EmpProfileController'
}
}
})
.state('app.tabs.service-request', {
url: "/articles",
views: {
'serviceRequest-tab': {
templateUrl: "templates/serviceRequest.html",
controller: 'articlesCtrl'
}
}
})
.state('app.tabs.colonies', {
url: "/colonies",
views: {
'colonies-tab': {
templateUrl: "templates/colonies.html",
controller: 'coloniesCtrl'
}
}
})
.state('app.foo', {
url: "/foo",
views: {
'menuContent': {
templateUrl: "templates/foo.html",
controller: 'fooCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/tabs/home');
$httpProvider.interceptors.push('sessionInjector');
});
}());
login.js (controller file)
angular.module('e2pro.LoginController', [])
// Employee Attendance Controller
.controller('LoginController', function($http, $scope, $state, $ionicHistory, $ionicLoading, $cordovaOauth, RequestsService){
console.log('Inside Login Controller');
var baseUrl=null;
$scope.credentials = {};
$scope.validationFailed = false;
$http.get('js/config.json')
.then(function(res){
baseUrl = res.data.server[res.data.mode];
});
// Method for user's default login
$scope.validateCredentials = function(form){
console.log('Form Validation start for login : '+form.$valid);
var attendance_require = null;
var emp_attendance_status = null;
// Setting module data element for the api request
$scope.credentials.module = 'user_login';
$scope.credentials.pageId = 1548;
// Check form validation status & move control accordingly
if(!form.$valid)
{
return false;
}
// Show spinner animation
$ionicLoading.show({
template: '<ion-spinner icon="android"></ion-spinner>'
});
$http({
method: 'POST',
url: baseUrl+'/S/E2Pro_MobileApiEndPoint.php',
data : $scope.credentials
}).then(function successCallback(response) {
if(response['data']['status'] === 'success')
{
session_id = response['data']['data']['session_id'];
user_id = response['data']['data']['user_id'];
route_to = response['data']['data']['route_to'];
attendance_require = response['data']['data']['attendance_require'];
emp_attendance_status = response['data']['data']['emp_attendance_status'];
window.localStorage.setItem("session_id", session_id);
window.localStorage.setItem("user_id", user_id);
window.localStorage.setItem("user_login_type", 'default');
// Hide Spinner before redirecting to home page
$ionicLoading.hide();
// Redirecting to home page
if(route_to === 'home'){
$state.go('app.tabs.home');
return false;
}
}
else
{
// Hide Spinner before redirecting to home page
$ionicLoading.hide();
// Show message for email id & password miss match
$scope.validationFailed = true;
}
}, function errorCallback(response) {
// console.log('Error occcur during user authentication');
// Hide Spinner before redirecting to home page
$ionicLoading.hide();
});
};
});
Home.js (Controller file)
angular.module('e2pro.HomeController', [])
// Employee Attendance Controller
.controller('HomeController', function($scope, $state, $location, $ionicHistory, $ionicSideMenuDelegate, $http, $ionicPopup, User, GeoAlert){
console.log('Inside Home Controller');
var baseUrl=null;
// Check application session. If it's found not exist redirect user to login page
if(window.localStorage.getItem("session_id") === "undefined" || window.localStorage.getItem("session_id") === null) {
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$state.go("login");
return false;
}
$scope.empName = '';
$scope.alertMsgBox = false;
$scope.alertMsgText = '';
$scope.employees = [];
$http.get('js/config.json')
.then(function(res){
baseUrl = res.data.server[res.data.mode];
});
// Method for showing Vendor page
$scope.showVendorPage = function(){
console.log('Clicked on vendor icon');
$state.go('app.tabs.vendor');
}
});
Home.html (template file)
<ion-view view-title="Home">
<ion-content class="has-tabs">
<div ng-controller='HomeController' >
<div class="row" style="margin-top:15px;">
<div class="col">
<img src="img/leave.png" ng-click="showVendorPage()">
<h5>Vendor</h5>
</div>
<div class="col">.col</div>
<div class="col">.col</div>
</div>
</div>
</ion-content>
</ion-view>

Related

redirection to profile page as soon as registration is successful

Not getting redirected to login page my profile page is an html and main is the login page. I tried redirecting it to both the pages but it keeps going to the catch block as soon as a relocation is provided.
angular.module('meanhotel').controller('RegisterController', RegisterController);
function RegisterController($http) {
var vm = this;
vm.register = function() {
var user = {
firstname: vm.firstname,
lastname: vm.lastname,
email: vm.email,
password: vm.password
};
if (!vm.email || !vm.password) {
vm.error = 'Please add email and password.';
} else {
if (vm.password !== vm.passwordRepeat) {
vm.error = 'Please make sure the passwords match.';
} else {
$http.post('/api/users/register', user).then(function(result) {
console.log(result);
// vm.message = 'Successful registration, please login!';
vm.error = '';
// $window.location.href('/main');
//$location.path('#!/profile');
$window.location.href = '/main.html';
}).catch(function(error) {
vm.error = "User already exists";
console.log(error);
});
}
}
}
};
app.js:
routing in app.js is as follows. Profile is a simple html page with a logout button. not sure if the user is getting passed to it as well. I am setting the user in another controller.
angular.module('meanhotel', ['ngRoute', 'angular-jwt']).config(config).run(run);
function config($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
$routeProvider
.when('/', {
templateUrl: 'angular-app/main/main.html',
access: {
restricted: false
}
})
.when('/register', {
templateUrl: 'angular-app/register/register.html',
controller: RegisterController,
controllerAs: 'vm',
access: {
restricted: false
}
})
.when('/profile', {
templateUrl: 'angular-app/profile/profile.html',
controller: LoginController,
controllerAs: 'vm',
access: {
restricted: true
}
})
.otherwise({
redirectTo: '/'
});
}
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix("");
}]);
function run($rootScope, $location, $window, AuthFactory) {
$rootScope.$on('$routeChangeStart', function(event, nextRoute, currentRoute) {
if (nextRoute.access !== undefined && nextRoute.access.restricted && !$window.sessionStorage.token && !AuthFactory.isLoggedIn) {
event.preventDefault();
$location.path('/');
}
});
}
Can you try once using
$location.path('/profile');

Angular JS ng-app in multiple spots

I have an angular app with a login page and a signup page and a dashboard that a user is able to access once they have logged in. Currently a user can you directly to the login page or the signup page, so I have a ng-app at the top of both pages. But this does not seem the right way to do things, and it doesn't make sense to initialize my app more than once. But if I only have the ng-app on the login page and a user goes directly to the signup page, the app wont be initialized and I wont have access to the controller for my signup page. How can I get around this?
I would like to just initialize my app once as from what I have read this is how it should be done.
Thank you
Put the ng-app in an index.html file, then have something like this in the body:
<body>
<div data-ui-view></div>
</body>
Then you can use ui-router or ng-route to switch 'states' (ie login, signup etc) and the 'view' will fill into the data-ui-view. Personally I find ui-router to be better, but either can do it.
Most of the time you have to use ng-app once per application. You can manage views using ngRoute module or with ui-router and you can find more options on it.
See example below, there are some extra things you can learn from.
angular.module('demoApp', ['ui.router'])
.run(function($rootScope, $state) {
$rootScope.$on('$stateChangeError', function(evt, to, toParams, from, fromParams, error) {
if (error.redirectTo) {
$state.go(error.redirectTo);
} else {
$state.go('error', {status: error.status})
}
})
})
.factory('userService', userService)
.config(routes);
function userService() {
var usersMock = {
'testUser': {
username: 'testUser',
password: '1234'
},
'testUser2': {
username: 'testUser2',
password: '1234'
}
};
var userService = {
user: undefined,
login: function(userCredentials) {
// later --> $http.post('auth', userCredentials).then(...)
// for demo use local data
var user = usersMock[userCredentials.username]
userService.user = ( user && ( user.password == userCredentials.password ) ) ?
user : undefined;
return user;
},
logout: function() {
userService.user = undefined;
}
}
return userService;
}
function routes($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('root', {
url: '',
abstract:true,
resolve: {
'user': function(userService) {
return userService.user; // would be async in a real app
}
},
views: {
'': {
templateUrl: 'layout.html',
},
'header#root': {
template: '<h1>header View<span ng-if="user"><button ng-click="logout()">logout</button></span><span ng-if="!user"><button ng-click="login()">login</button></span></h1>',
controller: function($scope, $state, user, userService) {
$scope.user = user;
$scope.login = function() {
$state.go('login');
};
$scope.logout = function() {
userService.logout();
$state.go('root.home', {}, {reload: true});
};
}
},
'footer#root': {
template: '<p>footer view</p>'
}
}
})
.state('root.home', {
url: '/',
views: {
'content': {
template: 'Hello at home'
}
}
})
.state('root.about', {
url: '/about',
views: {
'content': {
template: 'about view'
}
}
})
.state('root.restricted', {
url: '/restricted',
resolve: {
auth: function(userService, $q, $timeout) {
var deferred = $q.defer();
/* //with an async
return UserService.load().then(function(user){
if (permissionService.can(user, {goTo: state})) {
return deferred.resolve({});
} else {
return deferred.reject({redirectTo: 'some_other_state'});
}
}*/
$timeout(function() {
if ( angular.isUndefined(userService.user) ) {
return deferred.reject({redirectTo: 'login'});
}
else {
return deferred.resolve(userService.user);
}
});
return deferred.promise;
}
},
views: {
'content': {
template: 'this is only visible after login. Hello {{user}}!',
controller: function($scope, auth) {
$scope.user = auth.username;
}
}
}
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: function($scope, $state, userService) {
$scope.login = function(cred) {
var user = userService.login(cred);
if (angular.isUndefined(user)) {
alert('username or password incorrect.')
}
else {
$state.go('root.restricted');
}
};
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<div ng-app="demoApp">
<a ui-sref="root.home" href="#">home</a>
<a ui-sref="root.about" href="#">about</a>
<a ui-sref="root.restricted" href="#">restricted page</a>
<div ui-view>
</div>
<script type="text/ng-template" id="views/login.html">
<h1>Login</h1>
<label>Username</label><input ng-model="userCred.username"/>
<label>Password</label><input type="password" ng-model="userCred.password"/>
<button ng-click="login(userCred)">login</button>
</script>
<script type="text/ng-template" id="layout.html">
<div>
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
</div>
</script>
</div>

Resource no refresh when i use slow connection o 3G angular js

I 'm creating a mobile application based on angularjs . To load a list , I'm making a call to an API Rest. I am using a resource for doing this. When I 'm connected to the wifi it works perfectly , but when I use ยท g, the recuerso not call the API and always returns the previous value.
How I can refresh the application each time you call?
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});
Inject $ionicView and then:
$ioniView.enter(function(){
Exercises.query(function(data) {
$scope.exercises = data;
});
})

How to redirect to dashboard if user is logged in with AngularJS?

I am new in AngularJS. I want to redirect my page to dashboard if user is logged in. After login, i am getting access token which I am saving in cookies. I checked the solutions of Stack Overflow, then also my problem is not solved.
Here is my code:
app.js
(function(window){
var app= angular.module('customersApp',['ngRoute','ngCookies','ui.bootstrap']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/login', {
title: 'Login',
controller: 'loginController',
templateUrl: 'app/views/loginuser.html'
})
.when('/logout', {
title: 'Logout',
templateUrl: 'partials/login.html',
controller: 'loginController'
})
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'app/views/dynamic_table.html',
controller: 'dashboard'
})
.when('/verified_artists', {
title: 'Verified Artists',
templateUrl: 'app/views/verified_artists.html',
controller: 'artistController'
})
.when('/new_artists', {
title: 'New Request Artists',
templateUrl: 'app/views/new_artists.html',
controller: 'artistController'
})
.otherwise({
redirectTo: '/login'
});
}]);
window.app = app;
}(window));
loginController.js
app.controller('loginController', function ($scope,$http,$cookies,$cookieStore) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.signup = {};
$scope.doLogin = function (customer) {
$.post("websiteurl.com/admin_login",
{
user_email : $scope.login.email,
password : $scope.login.password
},
function(data,status){
data = JSON.parse(data);
console.log(data);
var someSessionObj = { 'accesstoken' : data.access_token};
$cookies.dotobject = someSessionObj;
$scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };
$cookieStore.put('obj', someSessionObj);
$scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
console.log($cookieStore.get('obj').accesstoken);
if(data.flag==10)
{
alert(data.error);
}
else
{
window.location.href = "#/dashboard";
}
})
};
});
try to look for route change event and check for cookie using cookie store...
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
// check for the cookie
// if present
// check next route
// if its login/signup page
// event.preventDefault(); (don't make the route change, redirect to dashboard)
// $location.path("/dashboard");
// if it is some other route
// allow it.
// if cookie not present
// $location.path("/login");
});

Issue with redirect on $location in Angularjs - Cannot read property 'path' of undefined

I have got plenty working, but at present I am stuck.
I have included a module for running parse.com authentication / login etc which I have added below.
I am trying to get the app to redirect on a successful login to /tab/friends by setting $location.path however I simply can't get it to work. In console I get Cannot read property 'path' of undefined.
I've been fighting this for two days, so any help would be super welcome :)
My parse related module:
// JavaScript Document
angular.module('AuthApp', [])
.run(['$rootScope', function( $scope, $location) {
$scope.scenario = 'Sign up';
$scope.currentUser = Parse.User.current();
$scope.location = $location;
console.log(location);
// $location.path('/tab/friends');
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
var randomValue = randomString(9);
$scope.signUp = function(form, $location) {
var user = new Parse.User();
user.set("email", form.email);
user.set("firstname", form.firstname);
user.set("lastname", form.lastname);
user.set("mobilenumber", form.mobilenumber);
user.set("username", form.email);
user.set("password", randomValue);
user.signUp(null, {
success: function(user) {
$scope.currentUser = user;
$scope.$apply();
},
error: function(user, error) {
alert("Unable to sign up: " + error.code + " " + error.message);
}
});
};
$scope.logIn = function(form, $routeParams, $location) {
Parse.User.logIn(form.username, form.password, {
success: function(user) {
console.log(location);
$location.path('/tab/friends');
$scope.currentUser = user;
},
error: function(user, error) {
alert("Unable to log in: " + error.code + " " + error.message);
}
});
};
$scope.logOut = function(form) {
Parse.User.logOut();
$scope.currentUser = null;
};
}]);
My app.'s code that starts everything up
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
// here we add our modules first then after that we start up our main app/module of 'starter' in the brackets to the right of that we have to include the modules that we want to load in too
angular.module('AuthApp', []);
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'AuthApp'])
.run(function($ionicPlatform,$rootScope,$location) {
$rootScope.location =$location;
$ionicPlatform.ready(function($routeParams,$location) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html"
})
// Each tab has its own nav history stack:
.state('tab.friends', {
url: '/friends',
views: {
'tab-friends': {
templateUrl: 'templates/tab-friends.html',
controller: 'FriendsCtrl'
}
}
})
.state('tab.friend-detail', {
url: '/friend/:friendId',
views: {
'tab-friends': {
templateUrl: 'templates/friend-detail.html',
controller: 'FriendDetailCtrl'
}
}
})
.state('tab.me', {
url: '/me',
views: {
'tab-me': {
templateUrl: 'templates/tab-me.html',
controller: 'meCtrl'
}
}
})
.state('tab.settings', {
url: '/settings',
views: {
'tab-settings': {
templateUrl: 'templates/tab-settings.html',
controller: 'SettingsCtrl'
}
}
})
.state('signup', {
url: '/signup',
templateUrl: 'templates/signup.html',
controller: 'SignupCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.state('firstview', {
url: '/firstview',
templateUrl: 'templates/firstview.html',
controller: 'FirstviewCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/firstview');
});
In your code you have the following :
// JavaScript Document
angular.module('AuthApp', [])
.run(['$rootScope', function( $scope, $location) {
You are using dependency injection in the .run. Unfortunately, you are not injecting $location properly.
Change it to this :
// JavaScript Document
angular.module('AuthApp', [])
.run(['$rootScope', '$location', function( $scope, $location) {

Categories