Reading data from firebase in angularfire - angularjs

I have an app where I need to store artists and their details in database.Now I want to retrieve all the artists and render some of their details in front end.How to do that.
Secondly, if I get the artist rating in some input field by using ng-model, then how to store that value in a particular artist to update details.
The database structure is:
{
"artists": {
"Atif":{
"name":"atif",
"rating":8
},
"Himesh":{
"name":"himesh",
"rating":5
}
}
}
and this is angular.js
(function()
{
var app = angular.module("myapp", ["firebase"]);
app.controller("maincontroller", function($scope, $firebaseObject,$firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists=ref.child("artists");
// download the data into a local object
$scope.data = $firebaseObject(ref);
// putting a console.log here won't work, see below
ref.on("value", function(snapshot)
{
console.log(snapshot.val());
}, function (errorObject)
{
console.log("The read failed: " + errorObject.code);
});
var artistsRef=new Firebase("https://gigstart.firebaseio.com//artists");
}); //end of controller
Now I want to render the name and rating of each artist in front end.Can I do something like
<div ng-repeat="artist in artists">
{{artist.name}}
{{artist.rating}}
</div>

You have a list of artists, which you want to ng-repeat over in your Angular view. You can accomplish that by:
app.controller("maincontroller", function($scope, $firebaseArray)
{
var ref = new Firebase("https://gigstart.firebaseio.com/");
var artists = ref.child("artists");
$scope.artists = new $firebaseArray(artists);
}
Please take a moment to go through the AngularFire quickstart before starting on your own project. This is covered in step 5.

Related

Selected city change on every page refresh and need to set again

User from front page ,select the city from below list and as per search product are displayed.
But after the every product displayed , page reload and City selected get changed to First city and user need to select again city for every search.
Need help how to overcome this issue and set the city to user selected ,not refreshed every time .
//Define an angular module for our app
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller('autocompleteController', function($scope, $http) {
$scope.cities = [
{name: 'London'},
{name: 'Paris'},
{name: 'Newyork'},
];
$scope.selectedCities = $scope.cities[0];
var initalizeproduct = function() {
$scope.products = $http.get("/getproduct/"+$scope.selectedCities.name).success(function(data){
$scope.products = data.products;
});
}
initalizeproduct($scope.products);
$scope.changeCity = function() {
initalizeproduct();
}
$scope.onSelectPart = function (item) {
$scope.selectedproducts = item;
window.location.href = "/product/"+$scope.selectedproducts.fields.slug;
};
});
From HTML Page :
<select ng-model="selectedCities" ng-change="changeCity()" ng-options="cities.name for cities in cities" style="background :transparent; border:0px; outline: none;">
</select>
Replace window.location.href = "..."; with:
$http
.get("/product/"+$scope.selectedproducts.fields.slug)
.then(function( ̶d̶a̶t̶a̶ response) {
var data = response.data;
// Get the HTML part from 'data' that you would like to display and add it to DOM
});
to begin with.

Need to add a child with value in Firebase using AngularJS

I need to insert in my Firebase using AngularJS a new child with value 0.
I try to insert using this command but doesn't work:
var ref = new Firebase(FBURL);
objectname = "name";
$scope.insert= ref.child("user/"+objectname);
$scope.insert.setvalue("Arthur");
result expected
firebaseID
|-------------user
|-----name:Arthur
You're not doing it the Angular way.
https://github.com/firebase/angularfire/blob/master/docs/guide/README.md
You could use Three-way Data Bindings:
var app = angular.module("sampleApp", ["firebase"]);
// a factory to create a re-usable Profile object
// we pass in a username and get back their synchronized data as an object
app.factory("Profile", ["$firebaseObject",
function($firebaseObject) {
return function(username) {
// create a reference to the database node where we will store our data
var ref = firebase.database().ref("rooms").push();
var profileRef = ref.child(username);
// return it as a synchronized object
return $firebaseObject(profileRef);
}
}
]);
app.controller("ProfileCtrl", ["$scope", "Profile",
function($scope, Profile) {
//your object id
var objectId = '-KSe_RHPYjhkjasjjh-o6';
// create a three-way binding to our Profile as $scope.profile
Profile(objectId).$bindTo($scope, "profile");
//now simple manipulate the $scope.profile variable
$scope.profile.name = "Arthur";
}
]);

Get JSON array object specific Id depending on which item i click on AngularJS

So i have a table with a list of teams, what i want to do is when i click on a team name it displays a new view with team details. There is 2 controllers, 1 to get league table and fixtures and then 1 for the team details. So far i have from the controller in the league table looped through the Json object array and gotten a list of links which contains the ID i need to pass in to the team details controller so i can specify which team it should display. Because the teams dont have the ID in the object i had to do it this way.
So the problem is that i can console.log all ID's but it only passes through the last ID logged. Which genereates the same team what ever team i click on. I want to get the specific ID for the team i click on and pass that to the team details controller id:.
I'm in the learning stages so excuse my poor code :).
If you see any improvements in my code writing please do let me know.
I get my data from:
http://api.football-data.org/
using the AngularJs factory library from:
https://github.com/JohnnyTheTank/angular-footballdata-api-factory
The View
<tbody>
<tr ng-repeat="team in teams.standing | filter:searchText | orderBy:orderByField:reverseSort">
// Where i want to somehow click on a team name and load that teams details
<td><strong>{{ team.teamName }}</strong></td>
</tr>
</tbody>
Controller1
.controller('AppCtrl', ['$scope', 'footballdataFactory', function($scope, footballdataFactory) {
$scope.date = new Date();
var apiKey = '***********************';
$scope.$back = function() {
window.history.back();
};
$scope.leagueId = function(id) {
$scope.id = id;
footballdataFactory.getLeagueTableBySeason({
id: $scope.id,
apiKey: apiKey, // Register for a free api key: http://api.football-data.org/register
}).success(function (data) {
$scope.teams = data;
$scope.leagueCaption = data.leagueCaption;
console.log("Get League", $scope.teams);
console.log('Loop through league and get team ids ----------------------------');
$scope.getTeamId = function(teamId) {
var dataLength = $scope.teams.standing.length;
for(var tUrl = 0; tUrl < dataLength; tUrl++) {
$scope.teamUrl = $scope.teams.standing[tUrl]._links.team.href.substr($scope.teams.standing[tUrl]._links.team.href.lastIndexOf('/') +1);
console.log('teamId: ' + $scope.teamUrl);
}
}
});
};
$scope.league = function(id) {
$scope.id = id;
footballdataFactory.getFixtures({
league: $scope.id,
apiKey: apiKey,
}).success(function(data){
$scope.games = data;
console.log("getFixtures", $scope.games);
});
};
}])
Controller2
// Team details controller
.controller('TeamCtrl', ['$scope', 'footballdataFactory', function($scope, footballdataFactory) {
var apiKey = '*************************';
footballdataFactory.getTeam({
id: $scope.teamUrl, ***Inserting the last 2 or 3 digits i get from the url***
apiKey: apiKey,
}).success(function(data){
$scope.teams = data;
$scope.name = data.name;
$scope.crestUrl = data.crestUrl;
$scope.squadMarketValue = data.squadMarketValue;
console.log("getTeam", $scope.teams);
});
footballdataFactory.getPlayersByTeam({
id: $scope.teamUrl,
apiKey: apiKey,
}).success(function(player){
$scope.players = player.players;
console.log("getPlayersByTeam", player);
});
}])
You can solve this problem easly with apiNG and the football-data plugin, that based on the same angular lib you even use. on the plugin page is a link to a working plnkr sample

Insert data into existing child firebase

First of all, I want to apologize for my poor English.
The last week I started to explore AngularJS in the Ionic framework with Firebase as backend. But I’ve stumbled upon a problem that I can’t solve for the past 3 days.
The purpose is when I chose a storage place and confirm it, an inventory will be created with a date and a link to the storage place to know to which storage place the inventory belongs. After that a list of products will be shown. When you chose a product, a new screen appears where you can add the amount of that product.
My problem is, I can create an inventory after confirmation, but it seems like I can’t insert the product with the amount inside the just created inventory.
Before insertion:
- Inventories
- Date: 1449767729166
- storage: "My Storage place 1"
I want my database looks like this after the insert:
- Inventories
- Date: 1449767729166
- storage: "My Storage place 1"
- Products:
- Name: Heineken
- Boxes: 12
- Bottles: 6
Here is my code:
addProducts.html
<div class="list">
<label class="item item-input item-floating-label">
<span class="input-label"><p>Aantal volle bakken/boxes</p></span>
<input type="text" placeholder="Aantal volle bakken/boxes" ng-model="products.boxes">
</label>
<br>
<label class="item item-input item-floating-label">
<span class="input-label"><p>Aantal (losse) flessen</p></span>
<input type="text" placeholder="Aantal (losse) flessen" ng-model="products.flessen">
</label>
<br>
<button class="button button-block button-dark" align="left" ng-click="AddProducts(products)">
Toevoegen
</button>
</div>
controllers.js:
.controller('AddProductCtrl', function($scope, $state, Inventory, Product) {
$scope.products = Inventory;
$scope.products = Product;
var now = Firebase.ServerValue.TIMESTAMP;
$scope.AddProducts = function(products) {
var query = Product.orderByChild(products.storage).equalTo('now');
query.once('child_added', function(snapshot) {
snapshot.ref().child('Products').push({
'Boxes' : fullBox,
'Bottles': losFles
});
});
}})
services.js
.factory('Product', ['$firebaseArray', function($firebaseArray) {
var addProductRef = new Firebase('https://testdb-1.firebaseio.co/Inventories/');
return $firebaseArray(addProductRef); }])
My Firebase structure:
Firebase structure
This is the error I got:
Error: Product.orderByChild is not a function
I already tried serveral things but with no success.
I'm really new to this. So, please point out what I did wrong.
Thanks in advance!
Your Product factory returns a $firebaseArray, which does not have an orderByChild() method.
I can't really figure out your use-case, but one way to solve the error message:
.factory('Product', ['$firebaseArray', function($firebaseArray) {
var addProductRef = new Firebase('https://testdb-1.firebaseio.co/Inventories/');
return addProductRef;
}])
So instead of returning a $firebaseArray this returns a Firebase reference, which has the orderByChild method you're looking to use.
And then:
$scope.AddProducts = function(products) {
var query = Product.orderByChild(products.storage).equalTo('now');
query.once('child_added', function(snapshot) {
snapshot.ref().child('Products').push({
'Boxes' : fullBox,
'Bottles': losFles
});
});
I believe the confusion comes from mixing up the Firebase SDK with the AngularFire API.
You properly create Products factory using a $firebaseArray(), but then you try to use it like a regular Firebase reference.
A $firebaseArray() takes in a Firebase references and wraps all of the child events (child_added, child_changed, etc...) and create a synchronized array.
You can try using a factory to get the products:
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.factory('productsByDate', function(rootRef, $q) {
return function productsByDate(storage) {
var deferred = $q.defer();
var productRef = rootRef.child('products'); // or however you get there
var localNow = new Date().getTime();
var query = Product.orderByChild(storage).equalTo(localNow);
query.once('value', function(snapshot) {
deferred.resolve(snapshot);
});
return deferred.promise;
};
});
Try this in your controller:
.controller('AddProductCtrl', function($scope, $state, Inventory, Product, productsByDate) {
$scope.products = Inventory;
$scope.products = Product;
var now = Firebase.ServerValue.TIMESTAMP;
$scope.AddProducts = function(products) {
// get your products by date
productsByDate(products.storage).then(function(snapshot) {
snapshot.ref().child('Products').push({
'Boxes' : fullBox,
'Bottles': losFles
});
});
});
});

angular firebase saving data as object

its my first time using angular with firebase.
I am having a hard time saving data as an object to firebase.
whenever i save a data, it doesn't provide index id or random generated id.
so first time name it saves the data and second time it overwrites the data because of not having any id.
here is my code
myApp.controller('MeetingsController', ['$scope','$firebaseObject', function ($scope, $firebaseObject) {
var ref = new Firebase('https://saddam.firebaseio.com/employees');
var obj = $firebaseObject(ref);
$scope.meetings = obj;
$scope.meetings.$loaded(function() {
console.log(obj);
});
$scope.addMeeting = function() {
obj.userinfo= {
meetingName : $scope.meetingname,
date : Firebase.ServerValue.TIMESTAMP
}
obj.$save();
}
}]);
Looking for some help

Resources