update/refresh angularjs ng-repeat with data from server - angularjs

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();
};

Related

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.

How to use Cordova Geolocation with OpenWeatherMap in Ionic?

I have an Ionic project connected to the OpenWeatherMap API, and I would like to use the Cordova plugin for geolocation; I tried to connect them, and I managed to be geolocalized, but impossible to get an answer from the API ...
However the API was configured correctly since I was able to get data before putting the plugin ...
Here is the code :
controllers.js =>
angular.module('weather')
.controller('WeatherCtrl', function($scope, $cordovaGeolocation, $http, OpenWeatherConfig) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}, function(err) {
});
$scope.state = false;
$scope.weatherData = {
icon: '',
main: '',
city: '',
description: '',
coord: '',
temp: ''
};
$scope.loadWeather = function(lat, lng) {
var url = OpenWeatherConfig.searchUrl + 'lat=' + lat + '&lon=' + lng + OpenWeatherConfig.units + OpenWeatherConfig.appid;
$http.get(url).success(function(data) {
$scope.weatherData.icon = OpenWeatherConfig.imgUrl + data.weather[0].icon + '.png';
$scope.weatherData.main = data.weather[0].main;
$scope.weatherData.city = data.name;
$scope.weatherData.description = data.weather[0].description;
$scope.weatherData.coord = data.coord;
$scope.weatherData.temp = data.main.temp;
$scope.state = true;
});
};
});
weather.html =>
<ion-view>
<ion-content overflow-scroll="false" class="weather-home">
<button class="button button-full button-calm" ng-click="loadWeather()">
Search
</button>
<div ng-if="state" class="forecast">
<img src="{{weatherData.icon}}" class="icon"/>
<label class="bigText">{{weatherData.main}}</label>
<div class="mainText">Town : {{weatherData.city}}</div>
<div class="mainText">Current conditions : {{weatherData.description}}</div>
<div class="mainText">Geographical coordinates : {{weatherData.coord}}</div>
<div class="bigText">{{weatherData.temp}} °C</div>
</div>
</ion-content>
</ion-view>
Nothing appears in the Firefox console, and I have only made changes in these files since the API was running ...
Thanks to "digit" to helping me find the way !
Here is the solution :
controllers.js =>
.controller('WeatherCtrl', function($scope, $cordovaGeolocation, $http, OpenWeatherConfig) {
$scope.state = false;
$scope.weatherData = {
icon: '',
main: '',
city: '',
description: '',
lat:'',
lon: '',
temp: ''
};
$scope.loadWeather = function() {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var url = OpenWeatherConfig.searchUrl + 'lat=' + lat + '&lon=' + lon + OpenWeatherConfig.units + OpenWeatherConfig.appid;
$http.get(url).success(function(data) {
$scope.weatherData.icon = OpenWeatherConfig.imgUrl + data.weather[0].icon + '.png';
$scope.weatherData.main = data.weather[0].main;
$scope.weatherData.city = data.name;
$scope.weatherData.description = data.weather[0].description;
$scope.weatherData.lat = data.coord.lat;
$scope.weatherData.lon = data.coord.lon;
$scope.weatherData.temp = data.main.temp;
$scope.state = true;
});
}, function(err) {
});
};
});
weather.html =>
<ion-view>
<ion-content overflow-scroll="false" class="weather-home">
<button class="button button-full button-calm" ng-click="loadWeather()">
Search
</button>
<div ng-if="state" class="forecast">
<img src="{{weatherData.icon}}" class="icon"/>
<label class="bigText">{{weatherData.main}}</label>
<div class="mainText">Town : {{weatherData.city}}</div>
<div class="mainText">Current Conditions : {{weatherData.description}}</div>
<div class="mainText">Geographical coordinates : {{weatherData.lat}}, {{weatherData.lon}}</div>
<div class="bigText">{{weatherData.temp}} °C</div>
</div>
</ion-content>
</ion-view>

AngularJS Firebase $add is not a function

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);
});
};
}]);

Having trouble passing _id parameter in Login.controller

I'm using angular-fullstack-generator.
I'm having trouble with passing _id parameter to some function.
What I'm trying to achieve is after I created a user I want to create another Data in schema referencing to user's id
therefore here is my code
'use strict';
class SignupVendorController {
//end-non-standard
constructor(Auth, $state, $http) {
this.Auth = Auth;
this.$state = $state;
this.$http = $http;
this.submitted = false;
}
//start-non-standard
register(form) {
this.submitted = true;
if (form.$valid) {
this.Auth.createUser({
firstName: this.user.firstName,
lastName: this.user.lastName,
email: this.user.email,
password: this.user.password,
role: 'vendor'
})
.then( Auth => {
this.vendor = Auth.getCurrentUser;
this.createVendor(this.vendor._id);
console.log('user is ' + this.vendor.firstName);
console.log('vendor created');
// Account created, redirect to home
this.$state.go('main');
})
.catch(err => {
err = err.data;
this.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, (error, field) => {
form[field].$setValidity('mongoose', false);
this.errors[field] = error.message;
});
});
}
}
createVendor(id) {
var vendor = {
category: ['publishing'],
_owner: id
}
this.$http.post('/api/vendors', vendor);
}
}
angular.module('aApp')
.controller('SignupVendorController', SignupVendorController);
I've tried several syntax modification but it all just got undefined variable on this.vendor.
like this, for instance
var vendor = Auth.getCurrentUser;
console.log('the user is ' + vendor.firstName);
the code cannot read either _id or firstName.
Any kind of help would be very appreciated.
Thank you !
Can you try this?:
this.vendor = Auth.getCurrentUser();
console.log('the user_id is ' + this.vendor._id);
In my App, that's working.

Resources