Firebase & Angular - Retrieve and display flattening data - angularjs

I have flattening data in my firebase with the following code. But when I want display favorite user posts list with ng-repeat, the template gets repeated a second time and comes out totally blank. How can I correct this?
"Post": {
"xKkdfjjfld856i": {
"name": "My first post",
"author": "Miguel"
},
"xKkdfjj556FGHh": { ... },
"xK499DF6FlHjih": { ... }
},
"users": {
"John": {
favorited_posts {
"xKkdfjjfld856i": true,
"xKkdfjj556FGHh": true
}
},
"Mia": { ... },
"Patrick": { ... }
},
HTML:
<div ng-repeat="post in favoritedPosts track by $index">
<div class="card post-card">
<h1>{{post.name}}</h1>
<p>{{post.author}}</p>
</div>
</div>
Controller :
var userRef = new Firebase("https://myApp.firebaseio.com/users")
var userFavoriteRef = userRef.child($scope.user_id).child("favorited_posts")
var favoritedPosts = $firebaseArray(userFavoriteRef)
userFavoriteRef.once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key();
var postRef = new Firebase("https://myApp.firebaseio.com/Posts")
postRef.child(childSnapshot.ref().key()).once('value', function(postSnapshot) {
console.log("Look",postSnapshot.val());
$scope.favoritedPosts = postSnapshot.val();
});
});
});

Try working with the $firebaseArray and $getRecord (documentation) to get the object value based on the object key. Then you will have everything you need without looping over assync calls.
Controller
var userRef = new Firebase("https://myApp.firebaseio.com/users")
var userFavoriteRef = userRef.child($scope.user_id).child("favorited_posts")
$scope.favoritedPosts = $firebaseArray(userFavoriteRef)
var postRef = new Firebase("https://myApp.firebaseio.com/Posts")
$scope.posts = $firebaseArray(postRef)
HTML
<div ng-repeat="post in favoritedPosts">
<div class="card post-card">
<h1>{{posts.$getRecord(post.$id).name}}</h1>
<p>{{posts.$getRecord(post.$id).author}}</p>
</div>
</div>

Related

Add an item to a firebase collection

I need to append an item in one or more collections in Firebase Database using angularfire (AngularJS)
For example, if I have:
users {
Marcelo: {
userid: 1
},
Javier: {
userid: 2
}
}
How can I append a new item in each collection, getting something like this?
users {
Marcelo: {
userid: 1
state: "enabled"
},
Javier: {
userid: 2
state: "enabled"
}
}
There is no specific AngularFire operation for this. But since AngularFire is just built on top of the Firebase JavaScript SDK, you use that to read the data and loop over it and then update each item.
A short snippet to get you started:
var ref = firebase.database().ref("users");
users.once("value", function(snapshot) {
snapshot.forEach(function(userSnapshot) {
userSnapshot.ref.update({ state: "enabled" });
});
});
In this sample we create a function to insert param in our object
//object = users object
//key = state or something else
//value = true or something else
var insertParam = function(object, key, value) {
for (var _key in object) {
object[_key][key] = value;
}
}
var app = angular.module("app", []);
app.controller("ctrl", [
"$scope",
function($scope) {
$scope.users = {
Marcelo: {
userid: 1
},
Javier: {
userid: 2
}
}
var insertParam = function(object, key, value) {
for (var _key in object) {
object[_key][key] = value;
}
}
insertParam($scope.users, "state", true);
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<ul>
<li ng-repeat="(key, option) in users">
{{key}}
<ul>
<li><b>userId:</b> {{option.userid}}</li>
<li><b>state:</b> {{option.state}}</li>
</ul>
</li>
</ul>
</div>

how i can remove item from multiple array in angularjs

i have function to remove item in multiple array angularjs. i use a factory like bellow
app.factory("array_obj", function () {
var currentUserIDs = {};
currentUserIDs.data = [];
currentUserIDs.city = [];
return currentUserIDs;
});
in controller have a function like this
$scope.deleteItem = function (index) {
currentUserIDs.city.splice(index, 1);
setUserID(); //insert data in url realtime
}
this work just for one array like city
i need a function to delete any item in array_obj
function simpleController($scope) {
$scope.data = {
"results1": [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] ,
"results2": [ { "id": 1, "name": "Test2" }, { "id": 2, "name": "Beispiel2" }, { "id": 3, "name": "Sample2" } ]
}
;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app>
<body ng-controller="simpleController">
<div data-ng-repeat="results in data">
<div data-ng-repeat="result in results">>
{{result.name}}</br>
</div>
</div>
</body>
</html>
Have Fun..!!!
In your controller:
$scope.all_results = data.results1.concat(data.results2);
In your view
<whatever ng-repeat="item in all_results">{{ item.id }} - {{ item.name }}</whatever>
You could work with an extra <div> with ng-repeat attribute in your HTML where in my example results is your data.
<div>
<div ng-repeat="result in results">
<div ng-repeat="item in result">{{item.name}}</div>
</div>
</div>
ok this work ... i have function to remove item in multiple array angularjs. i use a factory like bellow
app.factory("array_obj", function () {
var currentUserIDs = {};
currentUserIDs.data = [];
currentUserIDs.city = [];
return currentUserIDs;
});
in controller have a function like this
$scope.deleteItem = function (index) {
currentUserIDs.city.splice(index, 1);
setUserID(); //insert data in url realtime
}
this work just for one array like city
i need a function to delete any item in array_obj

Multiple custom filters in angular.js

I have a multi check box application which requires me to have multiple filters. I have been unable to use multiple filters even if I try to hard code an array to filter on. Here is an example I have created to try to make this work.
Working Example
HTML MARKUP:
<body ng-app="app">
<div ng-controller="MainCtrl">
<div ng-repeat="item in data.sessions | IndustryFilter : data.sessions.industry ">
{{item.id}}
</div>
</div>
Javascript
var app = angular.module("app", [])
.controller("MainCtrl", function ($scope, MatchedFilterList) {
$scope.data = {"sessions": [{
"id": "a093000000Vhzg7AAB",
"industry": ["Automovtive"],
"sessionName": "Keynote",
},
{
"id": "a093000000zg7AAB",
"industry": ["Automovtive", "Retail"],
"sessionName": "Keynote2",
},
{
"id": "a093er000f00zg7AAB",
"industry": ["Automovtive", "Retail", "Consumer Goods"],
"sessionName": "Keynote3",
}
]};
}).filter("IndustryFilter", function (MatchedFilterList) {
return function () {
var filtered = [];
angular.forEach(MatchedFilterList.industry, function (item) {
filtered.push(item);
});
console.log("Filter: Filter " + filtered)
return filtered;
};
})
.factory("MatchedFilterList", function(){
var matchedFilterList = {};
matchedFilterList.industry = {
"Automotive": "Automotive",
"Retail" : "Retail"
};
return matchedFilterList;
});

Single Controller for multiple html section and data from ajax request angularjs

I'm trying to show two section of my html page with same json data, i don't want to wrap both in same controller as it is positioned in different areas. I have implemented that concept successfully by using local json data in "angular service" see the demo
<div ng-app="testApp">
<div ng-controller="nameCtrl">
Add New
Remove First
<ul id="first" class="navigation">
<li ng-repeat="myname in mynames">{{myname.name}}</li>
</ul>
</div>
<div>
Lot of things in between
</div>
<ul id="second" class="popup" ng-controller="nameCtrl">
<li ng-repeat="myname in mynames">{{myname.name}}</li>
</ul>
JS
var testApp = angular.module('testApp', []);
testApp.service('nameService', function($http) {
var me = this;
me.mynames = [
{
"name": "Funny1"
},
{
"name": "Funny2"
},
{
"name": "Funny3"
},
{
"name": "Funny4"
}
];
//How to do
/*this.getNavTools = function(){
return $http.get('http://localhost/data/name.json').then(function(result) {
me.mynames = result.mynames;
return result.data;
});
};*/
this.addName = function() {
me.mynames.push({
"name": "New Name"
});
};
this.removeName = function() {
me.mynames.pop();
};
});
testApp.controller('nameCtrl', function ($scope, nameService) {
$scope.mynames = nameService.mynames;
$scope.$watch(
function(){ return nameService },
function(newVal) {
$scope.mynames = newVal.mynames;
}
)
$scope.addName = function() {
nameService.addName();
}
$scope.removeName = function() {
nameService.removeName();
}
});
jsfiddle
Next thing i want to do is to make a http request to json file and load my two section with data, and if i add or remove it should reflect in both areas.
Any pointers or exisisitng demo will be much helpful.
Thanks
The reason why only one ngRepeat is updating is because they are bound to two different arrays.
How could it happen? It's because that you have called getNavTools() twice, and in each call, you have replaced mynames with a new array! Eventually, the addName() and removeName() are working on the last assigned array of mynames, so you're seeing the problem.
I have the fix for you:
testApp.service('nameService', function($http) {
var me = this;
me.mynames = []; // me.mynames should not be replaced by new result
this.getNavTools = function(){
return $http.post('/echo/json/', { data: data }).then(function(result) {
var myname_json = JSON.parse(result.config.data.data.json);
angular.copy(myname_json, me.mynames); // update mynames, not replace it
return me.mynames;
});
};
this.addName = function() {
me.mynames.push({
"name": "New Name"
});
};
this.removeName = function() {
me.mynames.pop();
};
});
testApp.controller('nameCtrl', function ($scope, nameService) {
// $scope.mynames = nameService.mynames; // remove, not needed
nameService.getNavTools().then(function() {
$scope.mynames = nameService.mynames;
});
/* Remove, not needed
$scope.$watch(
function(){ return nameService },
function(newVal) {
$scope.mynames = newVal.mynames;
}
);
*/
$scope.addName = function() {
nameService.addName();
};
$scope.removeName = function() {
nameService.removeName();
};
});
http://jsfiddle.net/z6fEf/9/
What you can do is to put the data in a parent scope (maybe in $rootScope) it will trigger the both views ,And you don't need to $watch here..
$rootScope.mynames = nameService.mynames;
See the jsFiddle

Angularjs displaying json in Rails

I am trying to display a list of my donors - the html is:
<div class="panel">
<header>
<h1> Donor Information </h1>
</header>
<div class="content">
<div ng-app="Donor">
<div ng-controller="DonorCtrl">
<ul>
<li ng-repeat="donor in donors">{{donors.name_last | json}}</li>
</ul>
</div>
</div>
</div>
</div>
My Donor_controller.js is this:
var app;
app = angular.module("Donor", ["ngResource"]);
app.factory("Donors", [
"$resource", function($resource) {
return $resource("/donors", {}, {
update: {
method: "PUT"
}
});
}
]);
app.factory("Donor", [
"$resource", function($resource) {
return $resource("/donors/:id", {
id: "#id"
}, {
update: {
method: "GET"
}
});
}
]);
this.DonorCtrl = [
"$scope", "Donor", "Donors", function($scope, Donor, Donors) {
var donor;
$scope.donor = Donor.query();
$scope.donors = Donors;
$scope.addDonor = function() {};
donor = Donor.save($scope.newDonor)(function() {
return $scope.donors.push(donor);
});
return $scope.newDonor = {};
}
];
I am returning from my rails app via donors/1.json this:
{
"donor": {
"id": 1,
"tools_id": null,
"first_name": "Billy",
"last_name": "Bullard"
}
}
I get a list of dots when I view and it shows this on inspection (repeated):
<li ng-repeat="donor in donors" class="ng-scope ng-binding"></li>
How do I go from the json coming from Rails to the list of names in Angularjs?
You should remove | json from your bind and you want the donor's lastname, not the donors':
<li ng-repeat="donor in donors">{{donor.name_last}}</li>
Update 1
Also, you should have $scope.donors = Donors.query(); in your controller, not $scope.donor = ....

Resources