Hi I'm doing an application in Ionic Creator and I would like to retrieve one record from database that has given email address (userId) .
this is my code:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var userId = $ionicUser.details.email;
var ref = firebase.database().ref().child('/users/' + userId);
$scope.users = $firebaseArray(ref);
}
but if my code is like that it works fine but display all the data from database:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var ref = firebase.database().ref().child( "users");
// create a synchronized array
$scope.users = $firebaseArray(ref);
}
Any help would be super appreciated.
inject $firebaseObject into the controller and then do
var ref = firebase.database().ref().child('/users/');
$scope.user = $firebaseObject(ref.child(userId));
Related
My code is as shown below:
angular.module('xyz.homeController', [])
.controller('homeController', ['homeService', '$scope', '$location', '$modal', '$rootScope', '$localstorage', '$window', 'GoogleSignin'
function(homeService, $scope, $location, $modal, $rootScope, $localstorage, $window, GoogleSignin) {
])
angular.module('xyz.homeService', [])
.factory('homeService', function() {
var data = {};
var deliveryOption = 0;
var payCardOption = 0;
var orderId = '';
var restaurentID = '';
var orderInfo = {};
var orderItems = [];
data.setDeliveryOption = function(info) {
this.deliveryOption = info;
};
data.getDeliveryOption = function() {
return this.deliveryOption;
};
data.setOrderId = function(orderId) {
this.orderId = orderId;
};
data.getOrderId = function() {
return this.orderId;
};
data.setRestaurentId = function(id) {
this.restaurentID = id;
};
data.getRestaurentID = function() {
return this.restaurentID;
};
data.setOrderInfo = function(info) {
this.orderInfo = info;
};
data.getOrderInfo = function() {
return this.orderInfo;
};
data.setOrderItems = function(items) {
this.orderItems = items;
};
data.getOrderItems = function() {
return this.orderItems;
};
data.setPayCardOption = function(payCardOption) {
this.payCardOption = payCardOption;
};
data.getPayCardOption = function() {
return this.payCardOption;
};
return data;
});
Now when refresh is pressed , the route is called perfectly, I have handlede the information inside the route perfectly, but somehow I am not able to restore the state of app and as a result of that, I am not able to use homeService perfectly, how to get the reference of homeService perfectly, so that I can use it?
The term you're looking for is singleton.
All services in AngularJs are singletons but you are using factory which is initialized by controller.
This will solve your problem if you're swithcing from one controller to the other.
However if you're refreshing the page, the application will reboot.
There's no way around it than using localstorage, sessionstorage, cookies...etc.
These are available through the $window service.
I am creating a firebase blog app. I am experiencing a problem in a controller of mine where TypeError: $firebaseArray is not a function
I have been using $firebaseArray throughout the entire span of the app. I don't know how I broke it. I can show you the code to my controller.
app.controller('postController',["$scope", "$location","$routeParams","Blog","FBURL","Auth","authDataSrvc", "$firebaseObject", "$firebaseArray","FilePicker", "$window", function($scope,$location,$routeParams,Blog,FBURL,$firebaseArray,$firebaseObject,FilePicker,$window,Auth,authDataSrvc){
$scope.posts = Blog.allPosts; //All blog posts
var postId = $routeParams.postId;
if(postId){
$scope.selectedPost = getPost(postId); // gets unique object based on its id with get post function
}
function getPost(postId){
var ref = new Firebase(FBURL + "/" + postId);
return $firebaseArray(ref);
}
$scope.addPost = function(newpost){
Blog.addPost($scope.newpost);
$location.path('/'); //redirects to home page
console.log(newpost);
console.log($scope.posts); // all posts
$scope.newpost ={}; //reset the message
};
$scope.currentPost = function(postId){
Blog.getPost(postId);
console.log(postId);
};
$scope.editPost = function(post){
$scope.selectedPost.$save(post);
$location.path('/');
};
$scope.files = [];
$scope.pickFile = function(){
FilePicker.pickMultiple(
{
mimetype: 'image/*',
maxFiles: 4
},
$scope.onSuccess
);
};
$scope.onSuccess = function(Blobs,newpost){
$scope.files.push(Blobs); //push to filepicker
var imageURLs = []; //new image urls array
Blobs.forEach(function(file){
imageURLs.push(file.url); //inserts Blob.urls to imageURLs array
});
$scope.newpost['photo'] = imageURLs; //adds photo urls array to newpost.photo which stores to firebase 'newpost object'
console.log(Blobs.url);
$window.localStorage.setItem('files', JSON.stringify(Blobs.url));
};
// COMMENTS SECTION
/* {
}*/
$scope.createComment = function(post, message){
var profilePic;
var profileName;
/* Check to see social media provider before pushing that information */
if($scope.authData.provider === 'facebook'){
profilePic = $scope.authData.facebook.profileImageURL;
profileName = $scope.authData.facebook.displayName;
}
else if($scope.authData.provider === 'google'){
profilePic = $scope.authData.google.profileImageURL;
profileName = $scope.authData.google.displayName;
}
//console.log(profilePic,profileName);
var ref = new Firebase(FBURL + "/" + postId + "/comments/");
var fireCommentArray = $firebaseArray(ref);
return fireCommentArray.$set(
{
text: $scope.message.text,
pic: $scope.profilePic,
name: $scope.profileName
}
),
$scope.message = '';
};
$scope.removeComment = function(post, message) {
var commentForDeletion = new Firebase(FBURL + "/" + postId + "/comments/" + message.$id);
commentForDeletion.$remove();
};
Right now it errors out on getPost function, $scope.addCommentFunction which are both using $firebaseArray.$add() calls.
My app does have separated services and directives as well but everything seems to be intact with no errors.
Your $firebaseArray object gets injected as 9th parameter, but the variable $firebaseArray is the 6th parameter.
Try this instead:
app.controller('postController', [
"$scope", "$location", "$routeParams", "Blog", "FBURL",
"Auth", "authDataSrvc", "$firebaseObject", "$firebaseArray", "FilePicker",
"$window",
function(
$scope, $location, $routeParams, Blog, FBURL,
Auth, authDataSrvc, $firebaseObject, $firebaseArray, FilePicker,
$window
){
... or remove the ["$scope", "$location", "$routeParams", "Blog"... altogether if you don't mangle your variable names through a compressor or obfuscator.
I am POSTing a form and I want to redirect to my list page in case the form has no errors/is successfully persisted/saved to the db. How do I achieve that ?
app.controller('NoteCreateController',
['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
function($scope, Note, $routeParams, $location, ShareNoteScope) {
$scope.notes = ShareNoteScope.getScope().notes;
$scope.newNote = {};
$scope.createNote = function(note) {
var newNote = new Note(note);
newNote.$save(function(newNote) {
$scope.notes.unshift(newNote.note);
$scope.note = '';
$scope.errors = '';
}, function(newNote) {
$scope.errors = newNote.data;
// $location.path('/notes/'+newNote.note.id); where do I put this?
});
}
}]);
$save wraps success call with a callback. The piece of code above should do the trick.
newNote.$save(function (newNote) {
//success callback
$location.path('/notes/' + newNote.note.id);
}, function (newNote) {
$scope.errors = newNote.data;
});
I create service :
.factory('patientListBarService', function() {
var data = {
pages: 0,
total:0
};
return data;
})
my ctl 1:
.controller('patientCtl', ['$scope', '$http', 'patientListBarService', function($scope, $http, patientListBarService){
console.log(patientListBarService);
$scope.pages = patientListBarService.pages;
$scope.total = patientListBarService.total;
$scope.$watch('patientListBarService.pages', function(newVal, oldVal, scope) {
console.log('====pages:' + patientListBarService.pages);
$scope.pages = patientListBarService.pages;
});
$scope.$watch('patientListBarService.total', function(newVal, oldVal, scope) {
console.log('====total:' + patientListBarService.total);
$scope.total = patientListBarService.total;
});
}]);
my ctl 2:
controller('patientListCtl', ['$scope', 'patients', '$http', 'patientListBarService', function($scope, patients, $http, patientListBarService){
console.log("----patient list ctl----");
console.log(patients);
patientListBarService.pages = patients.config.pages;
patientListBarService.total = patients.config.total;
}]);
the ctl1 run before ctl2.
after ctl2 run, ctl1's
$scope.pages
$scope.total
display the right value on my view.
however, their display not change after I run ctl2 more times.
I am new to ng...
Anyone help me? thanks !!!
If you wrap your service data into an object, you don't need the watches and the values will be synced automatically
.controller("Test1", function($scope, Serv){
$scope.serv = Serv.data;
$scope.modify = function(){
$scope.serv.param1 = Math.random()*100;
$scope.serv.param2 = Math.random()*100;
}
})
.controller("Test2", function($scope, Serv){
$scope.serv = Serv.data;
})
.factory("Serv", function(){
var data = {
param1: '',
param2: ''
}
return {
data: data
}
});
jsbin
I am currently writing a code that is displaying the file from json to a charting JS.
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
viewAll.gauge = data;
});
$scope.value = viewAll.gauge[0].value;
However, I am having a hard time taking out the value from my variable array viewAll.gauge. I'm having an error in:
Error: viewAll.gauge[0] is undefined
#http://localhost:8080/js/directives/cpusagegauge.js:11:2
e#http://localhost:8080/js/angular.min.js:35:343
h/<.instantiate#http://localhost:8080/js/angular.min.js:35:474
ce/this.$get</<#http://localhost:8080/js/angular.min.js:68:140
x/<#http://localhost:8080/js/angular.min.js:54:226
q#http://localhost:8080/js/angular.min.js:7:384
x#http://localhost:8080/js/angular.min.js:54:89
g#http://localhost:8080/js/angular.min.js:48:28
g#http://localhost:8080/js/angular.min.js:48:1
g#http://localhost:8080/js/angular.min.js:48:1
x#http://localhost:8080/js/angular.min.js:55:10
g#http://localhost:8080/js/angular.min.js:48:28
x#http://localhost:8080/js/angular.min.js:55:10
z/<#http://localhost:8080/js/angular.min.js:61:261
l/k.success/<#http://localhost:8080/js/angular.min.js:73:32
Re/e/m.promise.then/L#http://localhost:8080/js/angular.min.js:99:147
Re/e/m.promise.then/L#http://localhost:8080/js/angular.min.js:99:147
Re/f/<.then/<#http://localhost:8080/js/angular.min.js:100:321
me/this.$get</g.prototype.$eval#http://localhost:8080/js/angular.min.js:111:1
me/this.$get</g.prototype.$digest#http://localhost:8080/js/angular.min.js:108:458
me/this.$get</g.prototype.$apply#http://localhost:8080/js/angular.min.js:112:323
g#http://localhost:8080/js/angular.min.js:73:285
x#http://localhost:8080/js/angular.min.js:77:322
Ne/</y.onreadystatechange#http://localhost:8080/js/angular.min.js:78:358
http://localhost:8080/js/angular.min.js
Line 93
BTW, my JSON file is pretty small.
[{
"value": "80"
}]
The problem is that the callback of $http.get() is called asynchronously. In your case viewAll.gauge = data;is called after $scope.value = viewAll.gauge[0].value;
The following should work:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.value = data.gauge[0].value;
});
})
Additionally if you want to update scope variables in async callbacks you have to wrap it in $scope.$apply(function() { //your code goes here });. Here is the full example:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.apply(function() {
$scope.value = data.gauge[0].value;
});
});
})