AngularJS Firebase $add is not a function - angularjs

I try to push a new record to my Firebase. But everytime I receive a console error like this:
$scope.contacts.$add is not a function
Here is my code:
app.controller('contactsCtrl',['$scope','$firebaseObject',function($scope,$firebaseObject){
var ref = new Firebase("https://<database_details>.firebaseio.com/contacts");
$scope.contacts = $firebaseObject(ref)
$scope.addContact = function(){
$scope.contacts.$add({
name: $scope.name,
address: $scope.address,
telephone: $scope.telephone,
company: $scope.company,
email: $scope.email
}).then(function(ref){
var id = ref.key();
console.log('contact added with Id: ' + id);
});
};
}]);

You should use $firebaseArray instead of $firebaseObject
app.controller('contactsCtrl','$scope','$firebaseArray',function($scope,$firebaseArray){
var ref = new Firebase("https://<database_details>.firebaseio.com/contacts");
$scope.contacts = $firebaseArray(ref)
$scope.addContact = function(){
$scope.contacts.$add({
name: $scope.name,
address: $scope.address,
telephone: $scope.telephone,
company: $scope.company,
email: $scope.email
}).then(function(ref){
var id = ref.key();
console.log('contact added with Id: ' + id);
});
};
}]);

Related

Adding automatically generated key in Firebase using Angular JS

I'm currently working with Angular 1.4.5 and Firebase 4.3.0 and have some questions need to ask.
I want to know that how can I add the key which is generated automatically by Firebase into the data of particular item.
For example, by following the tutorial, I've managed to store the user ID generated by Firebase using uid
my Firebase data structure:
And this is the code
myApp.factory('Authentication', ['$rootScope', '$location', '$firebaseObject','$firebaseAuth',function($rootScope, $location, $firebaseObject, $firebaseAuth){
var ref = firebase.database().ref();
var auth = $firebaseAuth();
var myObject;
auth.$onAuthStateChanged(function(authUser){
if(authUser){
var userRef = ref.child('users').child('accounts').child(authUser.uid);
var userObj = $firebaseObject(userRef);
$rootScope.currentUser = userObj;
}else {
$rootScope.currentUser = '';
}
});
myObject = {
login: function(user){
auth.$signInWithEmailAndPassword(
user.email,
user.password
).then(function(user){
$location.path('/home');
}).catch(function(error){
$rootScope.message = error.message;
});//signInWithEmailAndPassword
},//login
logout: function(){
return auth.$signOut();
}, //logout
requireAuth: function(){
return auth.$requireSignIn();
},//require Authentication
register: function(user){
auth.$createUserWithEmailAndPassword(
user.email,
user.password
).then(function(regUser){
var regRef = ref.child('users').child('accounts').child(regUser.uid).set({
date: firebase.database.ServerValue.TIMESTAMP,
regUser: regUser.uid,
firstname: user.firstname,
lastname: user.lastname,
email: user.email
}); //userinfo
myObject.login(user);
}).catch(function(error){
$rootScope.message = error.message;
});//createUserWithEmailAndPassword
}//register
};//return
return myObject;}]);//factory
This is the code i use to add item into Firebase (function uploadItem and uploadItem1)
pageControllers.controller('UploadController',['$scope', '$firebaseAuth', '$firebaseArray',
function($scope, $firebaseAuth, $firebaseArray){
var ref = firebase.database().ref();
var auth = $firebaseAuth();
auth.$onAuthStateChanged(function(authUser){
if(authUser){
var recipesRef = ref.child('users').child('accounts').child(authUser.uid).child('recipes');
var recipesInfo = $firebaseArray(recipesRef);
var recipes1Ref = ref.child('users').child('recipes');
var recipes1Info = $firebaseArray(recipes1Ref);
var favoritesRef = ref.child('users').child('accounts').child(authUser.uid).child('favorites');
var favoritesInfo = $firebaseArray(favoritesRef);
$scope.recipes = recipesInfo;
$scope.favorites = favoritesInfo;
$scope.uploadItem = function(){
recipesInfo.$add({
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
}//uploadItem
$scope.uploadItem1 = function(){
recipes1Info.$add({
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
}//uploadItem
$scope.addFavorite = function(name){
favoritesInfo.$add({
name: name,
// name: $scope.itemName,
// index: $scope.itemIndex,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
$scope.message = 'Success!';
$('#Popup').modal();
console.log(name);
});//promise
}//uploadItem
$scope.deleteFavorite = function(key){
favoritesInfo.$remove(key);
} //deleteFavorite
$scope.deleteRecipe = function(key){
recipesInfo.$remove(key);
} //deleteFavorite
}//authUser
});//onAuthStateChanged}]);//myAll.controller
I want to add the key of each item into its data like putting the uid into the users data but i don't know how.
what i understand from your question is that you want to store the auto generated key from the firebase into the items that you push like below,
If you want something like this, it can be done in two ways
1 ) Pure firebase Coding
$scope.uploadItem1 = function(){
var receipeInfoKey=recipes1Ref.push().key
or var receipeInfoKey=ref.child('users').child('recipes').push().key;
var receipeInfoObj={}
receipeInfoObj= {
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP,
receipeKey:receipeInfoKey
}
recipes1Ref .child(receipeInfoKey).set(receipeInfoObj)
or
ref.child('users').child('recipes').child(receipeInfoKey).set(receipeInfoObj)
.then(function(){
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
}//uploadItem
2 ) Angular fire
// This method will be like updating the recipes1Info object after the successful push
$scope.uploadItem1 = function(){
recipes1Info.$add({
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(recipes1Ref){
var receipePushedObj= recipes1Info.$getRecord(recipes1Ref.key);
// recipes1Ref.key this is the auto generated key after the successful push
if(receipePushedObj!=null){
receipePushedObj.receipeKey=recipes1Ref.key;
recipes1Info.$save(receipePushedObj);
}
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
here is the working sample of the first method I proposed.Js Fiddle Example

Firebase angularjs firebase current auth gets replaced when creating a new user

I am working on angular firebase web app, in which as soon as admin login, he can create users by his own.
When admin log in , he is authenticated with firebase.auth()
But what is happening is, as admin creates a new user, the current auth details(admin) gets replaced by newly created user. I want the user creation without creating a newer session
Have a look at my controller:
app.controller('UserAdd', ['$scope','$sessionStorage','$http','$firebaseAuth', '$firebaseArray', '$location' ,'$firebaseObject', 'FBURL', function($scope,$sessionStorage,$http,$firebaseAuth,$firebaseArray, $location ,$firebaseObject, FBURL){
var user = firebase.database().ref().child("users");
$scope.user_auth_data = firebase.auth().currentUser;
$sessionStorage.uID = $scope.user_auth_data.uid ;
$scope.access_points= [];
$scope.teams = [];
$scope.org_details = [];
user.child($sessionStorage.uID).child("OrganizationId").on('value',function(org_id){
$sessionStorage.org_id = org_id.val();
})
user.child($sessionStorage.uID).child("ImagePath").on('value',function(img){
$scope.user_image = img.val();
})
//access points
firebase.database().ref().child("organization").child($sessionStorage.org_id).child("access_points").on('value',function(access_points){
angular.forEach(access_points.val(),function(ap,key){
$scope.access_points.push({id:key,ssid:ap.SSID,bssid:ap.BSSID,display_name:ap.DisplayName,lat:ap.Latitude,lng:ap.Longitude});
})
});
var obj = $firebaseArray(firebase.database().ref().child("organization").child($sessionStorage.org_id).child("access_points"));
obj.$loaded(
function(data) {
},
function(error) {
console.error("Error:", error);
}
);
firebase.database().ref().child("organization").child($sessionStorage.org_id).child("teams").on('value',function(teams){
angular.forEach(teams.val(),function(team,key){
$scope.teams.push({id:key,team_name:team.TeamName,team_leader:team.TeamLeader,channel_name:team.ChannelName});
})
});
var obj = $firebaseArray(firebase.database().ref().child("organization").child($sessionStorage.org_id).child("teams"));
obj.$loaded(
function(data) {
},
function(error) {
console.error("Error:", error);
}
);
$scope.selectItem = function(){
};
//add user
$scope.addUser = function() {
firebase.auth().createUserWithEmailAndPassword($scope.Email, $scope.Password)
.then(function(user) {
//adding single values in user node
var ref = firebase.database().ref().child("users").child(user.uid);
ref.set({
EmployeeId: $scope.emp_id,
Contact: $scope.Contact,
DOB: $scope.date_of_birth,
Designation: $scope.Designation,
Email: $scope.Email,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
OrganizationId: $sessionStorage.org_id,
Gender: $scope.selectedGender,
IsAdmin: false
});
$scope.selectedAccess.forEach(function(access_values){ //adding nested access_points
var ref1 = firebase.database().ref().child("users").child(user.uid).child("AccessPoint").child(access_values.id);
ref1.set({
SSID: access_values.ssid,
BSSID: access_values.bssid,
DisplayName: access_values.display_name,
Latitude: access_values.lat,
Longitude: access_values.lng
});
});
$scope.selectedTeam.forEach(function(team_values){ //adding nested team
var ref2 = firebase.database().ref().child("users").child(user.uid).child("team").child(team_values.id);
ref2.set({
ChannelName: team_values.channel_name,
TeamName: team_values.team_name,
TeamLeader: team_values.team_leader
});
});
$scope.teams.forEach(function(team_values){
var ref3 = firebase.database().ref().child("organization").child($sessionStorage.org_id).child("channels").child(team_values.channel_name).child("info").child("users");
ref3.child(user.uid).set($scope.FirstName+" "+$scope.LastName);
var ref4 = firebase.database().ref().child("organization").child($sessionStorage.org_id).child("user_team").child(team_values.team_name).child(user.uid);
ref4.set($scope.FirstName+" "+$scope.LastName);
});
firebase.auth().sendPasswordResetEmail(user.email);
$location.path('/user_list');
}).catch(function(error) {
console.log(error);
});
};
}]);
Whats needs to be done to remain in same admin session instead of a new one?

angularfire $add not working

I'm trying to do a simple CRUD with ionic (v1) and angularfire. I can read and delete records but I need to edit and create. The actual problem is angularfire function $add`, this function doesn't do anything and doesn't return any error in the console. I have this code:
$scope.users = $firebaseArray(root.ref('/users/'));
$scope.user = {};
//Create
$scope.title = "New user"
$scope.button = "Create";
$scope.icon = "ion-person-add";
$scope.submit = function () {
var data = {
name: $scope.user.name,
username: $scope.user.username,
email: $scope.user.email,
street: $scope.user.street,
suite: $scope.user.suite,
city: $scope.user.city,
lat: $scope.user.lat,
lng: $scope.user.lng,
phone: $scope.user.phone,
website: $scope.user.website,
}
console.log(data);
$scope.users.$add(data).then(function (ref) {
console.log('contact added with Id: ' + id);;
})
Apparently the code is fine, but doesn't return console.log so maybe had some errors. Any ideas?
Well to find out if there is any error Javascript then takes to call back one for success and the other for failure something like the code below
$scope.user.$add(data).then(function (success){
return console.log(success);
}, function(error){
return console.log(error);
})
Now that's for then that way you can log returned errors
Error fixed.
$scope.users = $firebaseArray(root.ref('/users/'));
$scope.user = {};
//Create
$scope.title = "New user"
$scope.button = "Create";
$scope.icon = "ion-person-add";
$scope.submit = function () {
var data = {
name: $scope.user.name,
phone: $scope.user.phone,
email: $scope.user.email,
username: $scope.user.username,
city: $scope.user.city,
lat: $scope.user.lat,
lng: $scope.user.lng,
street: $scope.user.street,
suite: $scope.user.suite,
website: $scope.user.website,
zipcode: $scope.user.zipcode,
}
$scope.users.$add(data).then(function (response) {
if (response) {
$ionicPopup.alert({
title: '<div><i class="ion-checkmark-circled"></i></div>',
subTitle: '<h4>The user <b>' + data.name + '</b> is added.</h4>',
});
}
$scope.user=null;
With that all works properly and modal shows when we add user.

update/refresh angularjs ng-repeat with data from server

I try to buil a website to like some pictures.
I can load the picture, but I want to have a like system with who like the picture.
my problem was I have to refresh the page to see who like this picture and increment the count.
this my controller :
$scope.loadingpics = function (){
$http.get('/api/photos')
.success(function(awesomeThings) {
console.log(awesomeThings);
$scope.firstname = awesomeThings;
})
.error(function (err){
$scope.errors.other = err.message;
});
};
$scope.upVote = function(index){
$scope.vote = 1;
var ref = index;
var nom = index.url.substr(30, 40);
var num = index.vote + 1;
$http.put('api/photos/' + nom, {
email: email,
vote: num
})
.success(function (data) {
$scope.firstname = data;
$scope.loadingpics();
})
.error(function (err){
$scope.errors.other = err.message;
});
};
this is my view :
<li ng-repeat="image in firstname | orderBy: 'firstname'" ng-show="isLoggedIn()" class="thumbnail" title="Image 1" on-last-repeat>
<img ng-src="../assets/images/Pouce.png" ng-click="upVote(image)" data-toggle="popover" data-content="And here's some amazing content. It's very engaging. Right?" data-placement="right" title="Popover title">
</li>
this is my schema :
var PhotoSchema = new Schema({
url: String,
firstname: String,
email: [String],
info: String,
vote: Number,
active: Boolean
});
Thanks for your help :D
Instead of storing only the number of likes in your schema, store an array of object :
var PhotoSchema = new Schema({
url: String,
firstname: String,
email: [String],
info: String,
vote: [{
date: Date,
user: String
}],
active: Boolean
});
I just change my upVote function by adding a $scope.watch and $scope apply.
This is my example :
$scope.upVote = function(index){
$scope.vote = 1;
var ref = index;
var nom = index.url.substr(30, 40);
console.log(nom);
console.log(index.vote);
var num = index.vote + 1;
console.log(index);
$http.put('api/photos/' + nom, {
email: email,
})
.success(function (data) {
$scope.firstname = data;
})
.error(function (err){
$scope.errors.other = err.message;
});
$scope.$watch($scope.firstname, $scope.loadingpics());
$scope.apply();
};

AngularJS-MongoLab $resource update error

I am connecting AngularJS with MongoLab and trying to update the "users" collection.
AngularJS resource service:
angular.module("myApp.services", ["ngResource"])
.constant({
DB_URL: "https://api.mongolab.com/api/1/databases/mydb/collections/users/:id",
API_KEY: "[SOME_RANDOM_KEY]"
})
.factory("UsersService", ["$resource", "DB_URL", "API_KEY", function($resource, DB_URL, API_KEY) {
return $resource(DB_URL, { apiKey: API_KEY, id: "#_id.$oid" }, { update: { method: "PUT" }});
}]);
This is how I am trying to update my users collection:
angular.module("myApp", ["myApp.services"])
.controller("AppController", ["$scope", "UsersService", function($scope, UsersService) {
$scope.users = [];
$scope.getAllUsers = function() {
$scope.users = UsersService.query();
};
$scope.updateUser = function(user) { // user: firstName, lastName, email
//delete user._id;
UsersService.update({}, user, function() {
$scope.users = UsersService.query();
console.log("Users updated successfully");
}, function() {
console.log("Some problems updating the user", arguments);
});
};
}]);
When I try to update the user information, it throws an exception stating:
{ "message" : "cannot change _id of a document old:{ _id: ObjectId('[SOME_RANDOM_KEY]'), firstName: \"Anup\", lastName: \"Vasudeva\", email: \"anup.vasudeva#emal.com\" } new:{ _id: {}, firstName: \"Anup\", lastName: \"Vasudeva\", email: \"anup.vasudeva#email.com\" }"
I am new to MongoDB, so I don't understand why it is creating an empty _id object for the new user instance?
Try changing your $scope.updateUser function to the following:
$scope.updateUser = function (user) {
var userId = user._id.$oid;
user._id = undefined;
UsersService.update({id: userId}, user, function () {
$scope.users = UsersService.query();
console.log("Users updated successfully");
}, function () {
console.log("Some problems updating the user", arguments);
});
};
The update/replacement object ('user'), should not contain the _id property when being passed to UsersService.update(). Mongo will not replace the _id value, so the id will stay the same after the update.
One other thing that's changed in this function is that we're passing the user id as the first parameter of the UsersService.update() function so that mongo knows which document to update.

Resources