route angular in ionic app - ionic-framework

/**
*
* #TODO: Make several files for the controllers if we have so many script
*
*/
angular.module('starter.controllers', ['ui.router'])
.controller('HomeCtrl', function($scope, $stateParams) {
})
.controller('RegistreCtrl', function($scope, $stateParams) {
})
.controller('FacturerCtrl', function($scope, $stateParams) {
})
.controller('DocumentsCtrl', function($scope, $stateParams) {
})
.controller('ParametresCtrl', function($scope, $stateParams) {
})
//controller pour connection to API
.controller('LoginConnect', ['$scope','connecting','sendtoken','$state','$stateParams',
function($scope,connecting,sendtoken,$state){
$scope.user = {};
var users = $scope.user;
$scope.connect = function (users,$state) {
var log = $scope.user.login;
var pass = $scope.user.password;
var mydata = {};
connecting.login(log,pass).then(function(result){
console.log(result);
var montoken = result.data.token;
sessionStorage.setItem('token',montoken);
console.log(montoken);
});
var mytoken = sessionStorage.getItem('token');
console.log(mytoken);
sendtoken.send(mytoken).then(function(userdata){
$scope.datab = userdata;
if($scope.datab = userdata){
$state.go('app.registre');
};
// var datauser = sessionStorage.getItem('myuserdata');
// if (datauser != ''){
// $state.transitionTo("app.registre");
// };
});
};
}
// function($location){
// if()
// $location.url("/home");
// }
])
//factory pour aller chercher le token
.factory('connecting', ['$http','$q', function ($http,$q){
var ConnectingFactory = {};
ConnectingFactory.login = function(log,pass){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/login.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {login: log, password: pass}
})
.success(function(result){
deferred.resolve(result);
// var promise = deferred.promise;
// promise.then(function(result){
// var mydata = result["data"];
// console.log(mydata);
// }
//);
});
return deferred.promise;
};
return ConnectingFactory;
}])
//END factory pour aller chercher le token
//Factory pour envoyer le token
.factory('sendtoken', ['$http','$q', function ($http,$q){
var tokenreceipt = {};
tokenreceipt.send = function(mytoken){
var deferred = $q.defer();
$http({
method: 'POST',
url: "http://api.tiime-ae.fr/0.1/request/settings-get.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {token : mytoken}
})
.success(function(userdata){
deferred.resolve(userdata);
// var promise = deferred.promise;
// promise.then(function(result){
// var mydata = result["data"];
// console.log(mydata);
// }
//);
});
return deferred.promise;
};
return tokenreceipt;
}]);
//END Factory pour envoyer le token
;
and my app.js:
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html'
})
.state('app.login', {
cache:false,
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/form-connection.html',
controller: 'LoginConnect'
}
}
})
.state('app.registre', {
url: '/registre',
views: {
'menuContent': {
templateUrl: 'templates/registre.html',
controller: 'RegistreCtrl'
}
}
})
.state('app.home', {
url: '/home',
views: {
'menuContent': {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
}
}
})
.state('app.facturer', {
url: '/facturer',
views: {
'menuContent': {
templateUrl: 'templates/facturer.html',
controller: 'FacturerCtrl'
}
}
})
.state('app.documents', {
url: '/documents',
views: {
'menuContent': {
templateUrl: 'templates/documents.html',
controller: 'DocumentsCtrl'
}
}
})
.state('app.parametres', {
url: '/parametres',
views: {
'menuContent': {
templateUrl: 'templates/parametres.html',
controller: 'ParametresCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/login');
});
Hi, here is my problem, i don t know how to change the view only when i retrieve my data. It says : "Cannot read property 'path' of undefined". Because i want that : when my function is success, the path change and send me to the home page. Do you have an idea ? I would really appreciate !

You can create you factories in simple way and return promises to controller i think it's controllers job to handle promises.
And this will solve your routing problem also as the success will be the part of controller not of factory
factory('AuthHttpSvcs', function($http, $location, $rootScope) {
return {
login: function(loginData) {
//return the promise directly.
return $http({
method: 'POST',
url: 'YOUR_URL',
data: loginData
}).then(function(result) {
//returns object with every detail.
return result;
});
}
}
});

Related

Hosting a Forge Autodesk viewer on Github

I've an issue with the Forge viewer I'm developping : Im' trying to host it using Github-page, but it doesn't seem to work correctly.
The issue is on the File tree : when I load the viewer page from the Github pages, the file tree seems stuck on "Loading...". However, it correctly loads when I load the page from localhost.
The code of the File tree :
$(document).ready(function () {
prepareAppBucketTree();
$('#refreshBuckets').click(function () {
$('#appBuckets').jstree(true).refresh();
});
$('#createNewBucket').click(function () {
createNewBucket();
});
$('#createBucketModal').on('shown.bs.modal', function () {
$("#newBucketKey").focus();
})
$('#hiddenUploadField').change(function () {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
});
});
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.log(bucketKey)
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function prepareAppBucketTree() {
$('#appBuckets').jstree({
'core': {
'themes': { "icons": true },
'data': {
"url": '/api/forge/oss/buckets',
"dataType": "json",
'multiple': false,
"data": function (node) {
return { "id": node.id };
}
}
},
'types': {
'default': {
'icon': 'glyphicon glyphicon-question-sign'
},
'#': {
'icon': 'glyphicon glyphicon-cloud'
},
'bucket': {
'icon': 'glyphicon glyphicon-folder-open'
},
'object': {
'icon': 'glyphicon glyphicon-file'
}
},
"plugins": ["types", "state", "sort", "contextmenu"],
contextmenu: { items: autodeskCustomMenu }
}).on('loaded.jstree', function () {
$('#appBuckets').jstree('open_all');
}).bind("activate_node.jstree", function (evt, data) {
if (data != null && data.node != null && data.node.type == 'object') {
// $("#MyViewerDiv").empty();
var urn = data.node.id;
getForgeToken(function (access_token) {
jQuery.ajax({
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn + '/manifest',
headers: { 'Authorization': 'Bearer ' + access_token },
success: function (res) {
if (res.status === 'success') callByUrn('urn:'+urn);
else $("#MyViewerDiv").html('The translation job still running: ' + res.progress + '. Please try again in a moment.');
},
error: function (err) {
var msgButton = 'This file is not translated yet! ' +
'<button class="btn btn-xs btn-info" onclick="translateObject()"><span class="glyphicon glyphicon-eye-open"></span> ' +
'Start translation</button>'
$("#MyViewerDiv").html(msgButton);
}
});
})
}
});
}
function autodeskCustomMenu(autodeskNode) {
var items;
switch (autodeskNode.type) {
case "bucket":
items = {
uploadFile: {
label: "Upload file",
action: function () {
uploadFile();
},
icon: 'glyphicon glyphicon-cloud-upload'
}
};
break;
case "object":
items = {
translateFile: {
label: "Translate",
action: function () {
var treeNode = $('#appBuckets').jstree(true).get_selected(true)[0];
translateObject(treeNode);
},
icon: 'glyphicon glyphicon-eye-open'
}
};
break;
}
return items;
}
function uploadFile() {
$('#hiddenUploadField').click();
}
function translateObject(node) {
$("#MyViewerDiv").empty();
if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = node.parents[0];
var objectKey = node.id;
jQuery.post({
url: '/api/forge/modelderivative/jobs',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'objectName': objectKey }),
success: function (res) {
$("#MyViewerDiv").html('Translation started! Please try again in a moment.');
},
});
}
Please note that Github Pages are used for serving static pages without any special server-side logic. Your Forge application requires a server to talk to as well, for example, to obtain a list of buckets for the tree view (by making a request to /api/forge/oss/buckets).
You could potentially host your application's server-side logic on something like Heroku, and then have your static HTML/CSS/JavaScript page on Github talk to that server (for example, https://my-forge-app.herokuapp.com/api/forge/oss/buckets). Just be careful about CORS.

TypeError: Cannot read property ‘uid’ of undefined ionic-v1

I have the following question as to how I could be solving this problem with the property uid with authentication via facebook / firebase. This displays the error message in the command prompt according to the image.
Print Error Prompt
Services
'use strict';
app.factory('Auth', function ($firebaseAuth, $firebaseObject, $firebaseArray, $state, $http, $q, $cordovaOauth) {
var ref = firebase.database().ref();
var auth = $firebaseAuth();
var Auth = {
createProfile: function(uid, profile) {
return ref.child('profiles').child(uid).set(profile);
},
getProfile: function(uid) {
return $firebaseObject(ref.child('profiles').child(uid));
},
login: function() {
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('public_profile, email, user_location, user_birthday, user_photos, user_about_me');
// return auth.$signInWithPopup(provider)
// .then(function(result) {
$cordovaOauth.facebook("1455510817798096", ["public_profile", "email", "user_location", "user_birthday", "user_photos", "user_about_me"])
.then(function (result) {
//var accessToken = result.credential.accessToken;
var user = Auth.getProfile(result.user.uid).$loaded();
//ver ideia do tairone pra ver o que acontece
// var user = Auth.getProfile(result.user).$loaded();
user.then(function(profile) {
if (profile.name == undefined) {
var genderPromise = $http.get('https://graph.facebook.com/me?fields=gender&access_token=' + accessToken);
var birthdayPromise = $http.get('https://graph.facebook.com/me?fields=birthday&access_token=' + accessToken);
var locationPromise = $http.get('https://graph.facebook.com/me?fields=location&access_token=' + accessToken);
var bioPromise = $http.get('https://graph.facebook.com/me?fields=about&access_token=' + accessToken);
var imagesPromise = $http.get('https://graph.facebook.com/me/photos/uploaded?fields=source&access_token=' + accessToken);
var promises = [genderPromise, birthdayPromise, locationPromise, bioPromise, imagesPromise];
$q.all(promises).then(function(data) {
var info = result.user.providerData[0];
var profile = {
name: info.displayName,
email: info.email,
avatar: info.photoURL,
gender: data[0].data.gender ? data[0].data.gender : "",
birthday: data[1].data.birthday ? data[1].data.birthday : "",
age: data[1].data.birthday ? Auth.getAge(data[1].data.birthday) : "",
location: data[2].data.location ? data[2].data.location.name : "",
bio: data[3].data.about ? data[3].data.about : "",
images: data[4].data.data
}
Auth.createProfile(result.user.uid, profile);
//mudar a profile tambem mudando ideia tairone
//Auth.createProfile(result.user, profile);
});
}
});
});
},
logout: function() {
return auth.$signOut();
},
getAbout: function(access_token) {
return $http.get('https://graph.facebook.com/me?fields=bio&access_token=' + access_token);
},
getAge: function(birthday) {
return new Date().getFullYear() - new Date(birthday).getFullYear();
},
requireAuth: function() {
return auth.$requireSignIn();
},
getProfilesByAge: function(age) {
return $firebaseArray(ref.child('profiles').orderByChild('age').startAt(18).endAt(age));
},
getProfiles: function(){
return $firebaseArray(ref.child('profiles'));
}
};
auth.$onAuthStateChanged(function(authData) {
if(authData) {
console.log('Este usuario ja se encontra logado!');
} else {
$state.go('login');
console.log('Este usuario ainda nao se encontra logado no aplicativo da cleo.');
}
});
return Auth;
});
Controller
'use strict';
app.controller('AuthCtrl', function(Auth, $state) {
var auth = this;
auth.login = function() {
console.log('Usuario clicou no botao para realizar login!');
// return Auth.login().then(function(user) {
return Auth.login(function(user) {
$state.go('app.home');
});
};
auth.logout = function() {
Auth.logout();
};
});

Unable to receive email address in sailsjs from passportjs

I'm unable to get the email address from facebook when i'm making the following call...
// https://developers.facebook.com/docs/
// https://developers.facebook.com/docs/reference/login/
facebook: function(req, res) {
passport.authenticate('facebook', { scope : ['email'] }, function(err, user) {
req.logIn(user, function(err) {
if (err) {
return;
}
res.redirect('/');
return;
});
})(req, res);
},
This is how the response is handled and is basically the PassportJS docs code.
customMiddleware: function(app) {
passport.use(new FacebookStrategy({
clientID: "5xxxxxxxxxxxxx6",
clientSecret: "exxxxxxxxxxxxxxxxxxxxxxxxxxxd9",
callbackURL: "http://localhost:1337/auth/facebook/callback"
}, verifyHandler));
app.use(passport.initialize());
app.use(passport.session());
}
And here is the handler.
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy;
var verifyHandler = function(token, tokenSecret, profile, done) {
process.nextTick(function() {
sails.log.info(profile);
Serviceseeker.findOne({uid: profile.id}, function(err, serviceseeker) {
if (serviceseeker) {
return done(null, serviceseeker);
}
else {
var data = {
provider: profile.provider,
uid: profile.id,
name: profile.displayName
};
if (profile.emails && profile.emails[0] && profile.emails[0].value) {
data.email = profile.emails[0].value;
}
if (profile.name && profile.name.givenName) {
data.firstName = profile.name.givenName;
}
if (profile.name && profile.name.familyName) {
data.lastName = profile.name.familyName;
}
Serviceseeker.create(data, function(err, serviceseeker) {
return done(err, serviceseeker);
});
}
});
});
};
And this is the response that I'm getting
info: info: { id: '1xxxxxxxxxxxxxx9',
username: undefined,
displayName: 'Txxxx Slxxxxn',
name:
{ familyName: undefined,
givenName: undefined,
middleName: undefined },
gender: undefined,
profileUrl: undefined,
provider: 'facebook',
_raw: '{"name":"Txxxx Slxxxxn","id":"1xxxxxxxxxxxxxx9"}',
_json: { name: 'Txxxx Slxxxxn', id: '1xxxxxxxxxxxxxx9' } }
Did you try:
passport.use(new FacebookStrategy({
clientID: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
callbackURL: "http://www.example.com/auth/facebook/callback"
passReqToCallback : true,
profileFields: ['id', 'emails', 'name'] //This
},

Ionic Multiple Modals only last showing

I have tried adding multiple modals to my project.
The problem is that only the last modal view shows up, no matter which one I call.
Here's the code:
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
$scope.modal1Data = {};
$ionicModal.fromTemplateUrl('templates/modal1.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.closeModal1 = function() {
$scope.modal.hide();
};
$scope.model1 = function() {
$scope.modal.show();
};
$scope.doModal1 = function() {
console.log('Doing Modal1', $scope.modal1Data);
$timeout(function() {
$scope.closeUseful();
}, 1000);
};
$scope.modal2Data = {};
$ionicModal.fromTemplateUrl('templates/modal2.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.closeModal2 = function() {
$scope.modal.hide();
};
$scope.model2 = function() {
$scope.modal.show();
};
$scope.doModal2 = function() {
console.log('Doing Modal2', $scope.modal2Data);
$timeout(function() {
$scope.closeUseful();
}, 1000);
};
}) //end controller
How can I fix this?
The wrong point is your $scope.modal variable. Because you are trying to access 2 modal into 1 variable.
Fix like this:
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
$scope.modal1Data = {};
$ionicModal.fromTemplateUrl('templates/modal1.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.closeModal1 = function() {
$scope.modal.hide();
};
$scope.model1 = function() {
$scope.modal.show();
};
$scope.doModal1 = function() {
console.log('Doing Modal1', $scope.modal1Data);
$timeout(function() {
$scope.closeUseful();
}, 1000);
};
$scope.modal2Data = {};
$ionicModal.fromTemplateUrl('templates/modal2.html', {
scope: $scope
}).then(function(modal) {
//Fix this line, changed the variable name to different name.
$scope.modal2 = modal;
});
$scope.closeModal2 = function() {
$scope.modal2.hide();
};
$scope.model2 = function() {
$scope.modal2.show();
};
$scope.doModal2 = function() {
console.log('Doing Modal2', $scope.modal2Data);
$timeout(function() {
$scope.closeUseful();
}, 1000);
};
}) //end controller
Create a service like this:
.service('modalService', function($ionicModal) {
this.openModal = function(id) {
var _this = this;
if(id == 1) {
$ionicModal.fromTemplateUrl('templates/search.html', {
scope: null,
controller: 'SearchCtrl'
}).then(function(modal) {
_this.modal = modal;
_this.modal.show();
});
} else if(id == 2) {
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
} else if( id == 3) {
$ionicModal.fromTemplateUrl('templates/signup.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
}
};
this.closeModal = function() {
var _this = this;
if(!_this.modal) return;
_this.modal.hide();
_this.modal.remove();
};
})
and call the modal with an ng-click like this:
ng-click="modalService.openModal(1)"

Modal open with angualrjs route

Hey I am working with bootstrap modal and calling it in angularjs. Its working good. Only the problem is that how can I route modal in angularjs routing. My Code:
Inside Controller
var modalInstance = $modal.open({
templateUrl: 'webpages/home/loginModal.html'
});
modalInstance.result.then(function () {
}, function () {
});
Inside Routing
.when('/login', {
templateUrl: function($routeParams) {
return 'sitepages/home/home.html';
},
controller: 'PageViewController',
reloadOnSearch: false
})
Its just example of routing how I am doing it, I need to find routing for modal.
You can use states for this purposes
$stateProvider.state("items.add", {
url: "/add",
onEnter: ['$stateParams', '$state', '$modal', '$resource', function($stateParams, $state, $modal, $resource) {
$modal.open({
templateUrl: "items/add",
resolve: {
item: function() { new Item(123).get(); }
},
controller: ['$scope', 'item', function($scope, item) {
$scope.dismiss = function() {
$scope.$dismiss();
};
$scope.save = function() {
item.update().then(function() {
$scope.$close(true);
});
};
}]
}).result.then(function(result) {
if (result) {
return $state.transitionTo("items");
}
});
}]
});
More details: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state
You don't need the routing for it
app.controller("ACtrl", ['$scope','$http', '$log', '$modal',
function($scope, http, $log, $modal){
$scope.OpenModel = function () {
var param = { appId: 1, price: 2.5 };
var modalInstance = $modal.open({
size: 'lg',
backdrop: 'static',
templateUrl: 'webpages/home/loginModal.html',
controller: 'modalCtrl',
resolve: {
data: function () { return param; }
}
});
modalInstance.result.then(function (response) {
//Do whatever you want to do with reponse
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}
///Add your modal control here
app.controller("modalCtrl", ['$scope','$http', '$modalInstance', 'data',
function($scope, http, $modalInstance, data){
// rest of the code goes here
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
}