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;
});
})
Related
When my app loads, I like to load a specific view based on the data stored on a SQLite database table. My database structure and my scenario is as below:
SQLite Database: myapp.db
Table: settings
Table fields: api_key, active_user_id
When the app loads, I would like to fetch the data of 'api_key' and 'active_user_id' from the SQLite table.
Scenario 1: if the 'api_key' is null or '', I need to load the 'registration' view.
Scenario 2: if the 'api_key' is 'not empty' and the 'active_user_id' is 'empty' or '0', then I need to load the 'login' view
Scenario 3: if the 'api_key' is 'not empty' and the 'active_user_id' is > 0, then I need to load the 'dashboard' view.
Here is my app.js
(function() {
var app = angular.module('MyApp', ['ionic', 'ngCordova']);
var db = null;
app.controller('RegistrationCtrl', function($scope, $cordovaSQLite) {
//properties and functions goes in here
});
app.controller('LoginCtrl', function($scope, $cordovaSQLite) {
//properties and functions goes in here
});
app.controller('DashboardCtrl', function($scope, $cordovaSQLite) {
//properties and functions goes in here
});
app.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
window.plugins.sqlDB.copy("myapp.db", 0, function() {
db = $cordovaSQLite.openDB("myapp.db");
}, function(err) {
db = $cordovaSQLite.openDB("myapp.db");
});
});
});
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('registration', {
url: '/registration',
templateUrl: 'templates/registration.html',
controller: 'RegistrationCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardCtrl'
});
$urlRouterProvider.otherwise('/registration');
});
}());
Where do I write the code to fetch the value of the api_key and active_user_id when the app loads?
How do I load a specific view based on the value of api_key and active_user_id, as per the scenarios mentioned above?
Any help would be really appreciated.
I have been making an app in AngularJS with Angular-ui-router based on Ionic Framework. It works perfect on the desktop in every web browser, but it does not show anything on my mobile (after build I run it on 2 devices). The problem is that it doesn't load template inside ui-view.
I have got an index.html file, the body section is below (in head section there is everything included):
<body ng-app="starter">
<div ui-view=""></div>
</body>
And the part of app.js - run and config.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
.run(function($ionicPlatform, $rootScope, $location) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
history.back();
};
})
.config(function($stateProvider, $urlRouterProvider) {
"use strict";
$stateProvider
.state('connectionCheck', {
url: '/',
controller: ['$scope', '$location', '$http',
function($scope, $location, $http) {
$http.get('http://pingurl.com')
.success(function(data) {
jdata = data;
if (data.status === "success") {
$location.path('/login');
}else{
$location.path('/error');
}
})
.error(function() {
$location.path('/error');
});
$scope.retry = function() {
$location.path('/');
};
}
]
})
.state('login', {
url: '/login',
templateUrl: 'login.html'
})
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: ['$scope', '$location', '$localStorage',
function($scope, $location, $localStorage) {
$scope.username = $localStorage.username;
$scope.token = $localStorage.token;
$scope.email = $localStorage.email;
$scope.goToAlerts = function() {
$location.path('/alerts');
};
$scope.goToSettings = function() {
$location.path('/settings');
};
$scope.goToLocation = function() {
$location.path('/location');
};
$scope.goToSymptoms = function() {
$location.path('/symptoms');
};
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return "active"
} else {
return ""
}
};
}
]
})
.state('error', {
url: '/error',
templateUrl: 'error.html'
})
.state('register', {
url: '/register',
templateUrl: 'register.html',
})
.state('push', {
url: '/push',
templateUrl: 'push.html',
})
.state('alerts', {
url: '/alerts',
templateUrl: 'alerts.html'
})
.state('newSymptom', {
url: '/newSymptom',
templateUrl: 'newsymptom.html'
})
.state('symptoms', {
url: '/symptoms',
templateUrl: 'symptoms.html'
})
.state('newAlert', {
url: '/newalert',
templateUrl: 'newalert.html'
})
.state('settings', {
url: '/settings',
templateUrl: 'settings.html'
})
.state('location', {
url: '/location',
templateUrl: 'location.html'
});
$urlRouterProvider.otherwise('/');
}).
//some controllers goes here
What I have already checked/tried to do?
I put example content to index.html - it worked.
I tried chanage the name of ui-view and add them in templateURL values of each state.
I changed the .html files to exlude error in them, but it did not helped.
Can anyone more experienced with Ionic/Angular give me a hint what is wrong here?
I seem to notice that it's often due to the modules you're loading in. So It's likely in this line.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
Try checking each module by making sure:
You added it to your index.html
it's being called correctly
it's up to date
You can figure out by removing each, one at a time and then seeing if it works on the device.
Also know that AngularJS out of the box uses AngularUI Router and this uses a thing called routing for views. The UI-Router uses a thing called states that is the most used but the unofficial way for AngularJS and Ionic uses their own view state system that is basically the same thing as the UI-Router just with the Ionic namespace. So that is something you need to look up or you may find yourself running into a lot of walls during you builds because you are calling ui.router and I bet it's what's confusing your app, so remove it.
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");
});
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) {
In my HTML, I have the following two links, but when I click them or try to enter them into the browser, my new ui-router code is redirecting them to the otherwise url I have specified. Why is this?
Folders
Clients
//Setting up route
window.app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to "/"
$urlRouterProvider.otherwise("/asfasfsa");
// Now set up the states
$stateProvider
.state('root', {
url: "/",
templateUrl: 'views/index.html',
resolve: { factory: setRoot }
})
.state('dashboard', {
url: "/dashboard",
templateUrl: 'views/dashboard/dashboard.html',
resolve: { factory: checkAuthentication }
})
.state('folders-show', {
url: "/folders/:folderId'",
templateUrl: 'views/dashboard/folders/view.html',
resolve: { factory: checkAuthentication }
})
.state('clients-list', {
url: "/clients'",
templateUrl: 'views/clients/list.html',
resolve: { factory: checkAuthentication }
})
});
// Check if user is logged in
var checkAuthentication = function ($q, $location) {
if (window.user) {
console.log(window.user);
return true;
} else {
console.log("Not logged in...")
var defered = $q.defer();
defered.reject();
$location.path("/");
return defered.promise;
}
};
// Set Root URLs
var setRoot = function ($q, $location) {
if (window.user) {
var defered = $q.defer();
defered.reject();
$location.path("/dashboard");
return defered.promise;
} else {
return true;
}
};
// Setting HTML5 Location Mode
window.app.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix("!");
}
]);
Sorry, simple typos on the folder and clients urls were causing the issue.
Foiled by typos again!