Clearing input field on firebase function after angular submit - angularjs

The function works and submits the user input to my firebase "back-end" but I cannot figure out a clear function to empty out the input field after using ng-submit. The input is tied to the var "emailInput" with ng-model. Thanks for any suggestions!
var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
$scope.email.$add(email);
$scope.emailInput = '';
};

I needed to assign a key to the email input and also an empty object.
$scope.emailInput = {};
var newEmailref = new Firebase("https://archerthedog.firebaseio.com/email");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
$scope.email.$add(email);
$scope.emailInput = {};
};

See the Full code of mine it's working for me
var ref = firebase.database().ref();
var firebasedata = $firebaseObject(ref);
var messagesRef = ref.child("storeUserData");
var data = $firebaseArray(messagesRef)
$scope.createItem= function(user) {
data.$add(user).then(function(data) {
$scope.user = "";
var myPopup = $ionicPopup.show({
title: 'Dear User, Your Account has created Successfully',
});
$timeout(function() {
myPopup.close(); //close the popup after 6 seconds for some reason
}, 6000);
});
}
ref.orderByValue().on("value", function(data) {
data.forEach(function(takenData) {
console.log("The " + takenData.key + " rating is " +
takenData.val().email);
});
});

Your code just needs a small modification to use $scope.email = ""; instead of $scope.emailInput = '';:
var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
$scope.email.$add(email);
$scope.email = '';
};

i didn't get you.... If add a item in firebase database the database will create key value,
if you doing like this
var ref = firebase.database().ref('players/');
ref.orderByValue().on("value", function(data) {
data.forEach(function(takenData) {
console.log("The " + takenData.key + " rating is " +
takenData.val().email);
});
});
The console.log answer will be for takenData.key is some id value like
(-Ko7cGuymlshrS2JQEEC)
Then takenData.val().email) is an email address...

Related

JSON won't save on scope AngularJS

i have a problem with saving JSON on a scope, I have already a function saving a JSON into a scope and works perfectly but the second one won't save...
servicoLeituraPosts.php returns JSON with data
servicoLeituraComments.php returns JSON with data
both send JSON through URL correctly, and the first shows data on scope, but the second one doesn't and it's done exactly like the first one, so I don't understand what is going on.
1st one saves JSON into $scope.posts, it has data and i can print it
2nd one saves JSON into $scope.comments, if i print it, it is blank? Why? Thank you for help but I'm a beginner in AngularJS.
<script>
var app = angular.module('postsApp', []);
var interval;
app.controller('postsCtrl', function($scope) {
$scope.toggle = false;
$scope.texto = [];
$scope.comment = [];
$scope.comment = "";
$scope.comments = [];
$scope.posts = [];
$scope.texto = "";
$scope.idPost = 0;
$scope.showBox = function(p){
p.toggle = !p.toggle;
if(interval == 0){
interval = setInterval("angular.element($('#postsApp')).scope().servicoLeituraPosts()",1000);
}else{
clearInterval(interval);
interval = 0;
}
$scope.servicoLeituraComments(p);
console.log($scope.comments);
console.log($scope.posts);
};
$scope.iniciaTimer = function(){
interval = setInterval("angular.element($('#postsApp')).scope().servicoLeituraPosts()",1000);
};
$scope.servicoLeituraPosts = function(){
$.getJSON(
"servicoLeituraPosts.php",
{
},
function(jsonData)
{
$scope.posts = jsonData;
$scope.$apply();
});
};
$scope.servicoLeituraComments = function(p){
$.getJSON(
"servicoLeituraComments.php",
{
"idPost": p.idPost
},
function(jsonData)
{
$scope.comments = jsonData;
$scope.$apply();
});
console.log($scope.comments);
};
$scope.addPost = function(){
$.post(
"addPostRest.php",
{
"texto" : $scope.texto
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
$scope.addLike = function(idPost){
$.post(
"addLike.php",
{
"idPost" : $scope.idPost = idPost
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
$scope.addComment = function(p){
$.post(
"addComentarioRest.php",
{
"comment" : p.comment,
"idPost" : p.idPost
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
});
</script>
Found the solution, apparently there was a problem with the parameter recieved on POST which made the JSON invalid having no data
It looks like you are calling console.log($scope.comments); synchronously after calling $.getJSON(...), rather than waiting for the jsonData to be returned. At this point the $scope is yet to be updated.
Try moving the console.log into the callback:
function(jsonData)
{
$scope.comments = jsonData;
$scope.$apply();
console.log($scope.comments);
});

Two $firebaseArrays on one page & one ctrl

I would like to use two different $firebaseArrays on one view with one controller. But only one of them works and the other only works if i put him in his own controller.
from my factory file:
.factory("AlphaFactory", ["$firebaseArray",
function($firebaseArray) {
var ref = firebase.database().ref('alpha/');
return $firebaseArray(ref);
}
])
.factory("BetaFactory", ["$firebaseArray",
function($firebaseArray) {
var ref = firebase.database().ref('beta/');
return $firebaseArray(ref);
}
])
and my controller:
.controller('DemoCtrl', function($scope, AlphaFactory, BetaFactory) {
$scope.alphaJobs = AlphaFactory;
$scope.addalphaJob = function() {
$scope.alphaJobs.$add({
Testentry: $scope.loremipsum,
timestamp: Date()
});
$scope.alphaJob = "";
};
$scope.betaJobs = BetaFactory;
$scope.addbetaJob = function() {
$scope.betaJobs.$add({
Testentry2: $scope.dolorest,
timestamp: Date()
});
$scope.betaJob = "";
};
)}
Are you sure it is not a simple matter of a promise has not finished?
var alphaJobs = AlphaFactory;
alphaJobs.$loaded().then(function() {
// Do something with data if needed
$scope.alphaJobs = alphaJobs;
});
var betaJobs = BetaFactory;
betaJobs.$loaded().then(function() {
// Do something with data if needed
$scope.betaJobs = betaJobs;
});

Can't delete records from a table in angular JS

$scope.submitForm = function(){
$scope.users.push({
fname : $scope.fname,
lname : $scope.lname,
email : $scope.email,
password : $scope.password,
});
$scope.fname = ''; //clear the input after adding
$scope.lname = '';
$scope.email = '';
$scope.password = '';
localStorage.setItem('users', JSON.stringify($scope.users));
};
I am facing some issues while delete a record from a table using angular js. At the time of deletion its working fine but while refreshing the page it came back.
$scope.deleteUser = function(idx){
console.log(idx);
deleteUser = $window.confirm('Are you sure you want to delete the User?');
if(deleteUser){
$scope.users.splice(idx, 1);
console.log($scope.users);
}
};
$scope.deleteUser = function(idx){
console.log(idx);
deleteUser = $window.confirm
('Are you sure you want to delete the User?');
if(deleteUser){
$scope.users.splice(idx, 1);
console.log($scope.users);
}
};
Here you are not deleting it from localStorage, i am guessing $scope.users contains data from the API.What you can do is after deleting, you can update the localStorage with $scope.users again
localStorage.setItem('users', JSON.stringify($scope.users));
You should update your local storage values when you delete an user.
$scope.deleteUser = function(idx){
console.log(idx);
deleteUser = $window.confirm('Are you sure you want to delete the User?');
if(deleteUser){
$scope.users = $scope.users.splice(idx, 1);
localStorage.setItem('users', JSON.stringify($scope.users));
console.log($scope.users);
}
};

Firebase child_removed not working in real-time

I am following tutsplus Real time web apps with Angularjs and Firebase.
I have main.js (below) which allows me to add and change items in Firebase in real time with no refresh of the browser (in Chrome and Safari).
However when I delete a message from Firebase I have to refresh the browser for the message list to update - so not in real time. I can't see where the problem is.
/*global Firebase*/
'use strict';
/**
* #ngdoc function
* #name firebaseProjectApp.controller:MainCtrl
* #description
* # MainCtrl
* Controller of the firebaseProjectApp
*/
angular.module('firebaseProjectApp')
.controller('MainCtrl', function ($scope, $timeout) {
var rootRef = new Firebase('https://popping-inferno-9738.firebaseio.com/');
var messagesRef = rootRef.child('messages');
$scope.currentUser=null;
$scope.currentText=null;
$scope.messages=[];
messagesRef.on('child_added', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
console.log(snapshotVal);
$scope.messages.push({
text: snapshotVal.text,
user: snapshotVal.user,
name: snapshot.key()
});
});
});
messagesRef.on('child_changed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
function deleteMessageByName(name){
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
$scope.messages.splice(i, 1);
break;
}
}
}
function findMessageByName(name){
var messageFound = null;
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
messageFound = currentMessage;
break;
}
}
return messageFound;
}
$scope.sendMessage = function(){
var newMessage = {
user: $scope.currentUser,
text: $scope.currentText
};
messagesRef.push(newMessage);
};
});
The code that is invoked when a message is deleted from Firebase:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
This code never actually deletes the message from the HTML/DOM.
There is a convenient deleteMessageByName method to handle the deletion. So if you modify the above to this, it'll work:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
deleteMessageByName(snapshot.key());
});
});

Angular js not updating dom when expected

I have a fiddle for this, but basically what it's doing it geo-encoding an address that is input into a textbox. After the address is entered and 'enter' is pressed, the dom does not immediately update, but waits for another change to the textbox. How do I get it to update the table right after a submit?
I'm very new to Angular, but I'm learning. I find it interesting, but I have to learn to think differently.
Here is the fiddle and my controller.js
http://jsfiddle.net/fPBAD/
var myApp = angular.module('geo-encode', []);
function FirstAppCtrl($scope, $http) {
$scope.locations = [];
$scope.text = '';
$scope.nextId = 0;
var geo = new google.maps.Geocoder();
$scope.add = function() {
if (this.text) {
geo.geocode(
{ address : this.text,
region: 'no'
}, function(results, status){
var address = results[0].formatted_address;
var latitude = results[0].geometry.location.hb;
var longitude = results[0].geometry.location.ib;
$scope.locations.push({"name":address, id: $scope.nextId++,"coords":{"lat":latitude,"long":longitude}});
});
this.text = '';
}
}
$scope.remove = function(index) {
$scope.locations = $scope.locations.filter(function(location){
return location.id != index;
})
}
}
Your problem is that the geocode function is asynchronous and therefore updates outside of the AngularJS digest cycle. You can fix this by wrapping your callback function in a call to $scope.$apply, which lets AngularJS know to run a digest because stuff has changed:
geo.geocode(
{ address : this.text,
region: 'no'
}, function(results, status) {
$scope.$apply( function () {
var address = results[0].formatted_address;
var latitude = results[0].geometry.location.hb;
var longitude = results[0].geometry.location.ib;
$scope.locations.push({
"name":address, id: $scope.nextId++,
"coords":{"lat":latitude,"long":longitude}
});
});
});

Resources