Angularjs displaying json in Rails - angularjs

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 = ....

Related

Shopping Cart Application Using AngularJs controller

I'm doing a shopping cart with AngularJs, but I'm having trouble adding products to the shopping cart.
I think error is on my Controller:
My data.json:
{
"items": [
{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}
]
}
my controller.js :
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.products = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function(data) {
angular.forEach(data.items, function(item, index) {
$scope.products.push(item.product);
});
});
}
$scope.carts=[];
$scope.add_cart = function(product){
if(product){
$scope.carts.push({ p_name: product.name, p_valor:product.price.value,);
}
}
$scope.total = 0;
$scope.setTotals = function(cart){
if(cart){
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function(cart){
if(cart){
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
]);
my html:
<body ng-controller="ListCtrl" ng-app="list">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "add_cart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat = "cart in carts" ng-init = "setTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "remove_cart(cart)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
</body>
I need the button add to cart to work correctly, bringing the product name and the value of the product. I also need it to bring the total value and also need to remove the product when clicking button remove cart.
Ty for Help guys!
your controller.js file contain some syntax error. please check for any typo or syntax error in code before you throw your code into stackoverflow 's basket. anyway,
there are some point you need to remember when code.
camelCase is recommended in javascript. as per conventions
each function should dedicated to perform a specific task (personal opinion)
it's good to follow styleguide angularjs &
javascript
$scope, and $watch is for data binding, so you can use data in template or in other scopes like directive. data-binding is great and primary selling point of AngularJs, but it has some drawbacks.
and power comes with great responsibility. :wink
please have a look, here is a working live demo of your code.
var app = angular.module("list", []);
ListController.$inject = ["$scope", "$http"];
app.controller("ListCtrl", ListController);
function ListController($scope, $http) {
function onLoad() {
$scope.products = [];
$scope.carts = [];
$scope.total = 0;
// getProducts();
demoData();
}
onLoad();
$scope.addCart = addCart;
$scope.getTotals = getTotals;
$scope.removeCart = removeCart;
// hould remove when using in prod
function demoData() {
var data = {
"items": [{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}]
}
parseProducts(data.items);
}
function getProducts() {
$http.get('data.json')
.success(function(data) { parseProducts(data.items) })
}
function parseProducts(items) {
angular.forEach(items, function(item, index) {
$scope.products.push(item.product);
});
}
function addCart(product){
if(product){
$scope.carts.push({
p_name: product.name,
p_price:product.price.value
});
}
}
function getTotals(){
var initialValue = 0;
$scope.total = $scope.carts.reduce((x,y) => x + y["p_price"], initialValue);
}
function removeCart(i){
$scope.carts.splice(i, 1);
getTotals();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="list" ng-controller="ListCtrl">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "addCart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat="cart in carts track by $index" ng-init = "getTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "removeCart($index)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
<button ng-click="getTotals()">get totals</button>
</body>
I found some Syntax error
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http",
function ($scope, $http) {
$scope.products = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function (data) {
angular.forEach(data.items, function (item, index) {
$scope.products.push(item.product);
});
});
$scope.carts = [];
$scope.add_cart = function (product) {
if (product) {
$scope.carts.push({
p_name: product.name,
p_valor: product.price.value,
}); //Here syntax err
}
}
$scope.total = 0;
$scope.setTotals = function (cart) {
if (cart) {
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function (cart) {
if (cart) {
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
} //Here syntax err
]);

How to access child records of a firebase array dynamically using Angularfire

I am trying to implement a accordion using angularfire . I am able to retrieve the top level list ("A1","D1","R1")for display but I am unable to figure out how to retrieve the child for each accordion tab that is selected. For Eg if I select "D1", it should open up and display "C1", "H1".
Here is my data on firebase
{
"A1" : {
"B1" : 50
},
"D1" : {
"C1 " : 98,
"H1" : 12
},
"R1" : {
"RR1" : 67,
"RD1" : 54
}
}
My code
var app=angular.module("sampleApp",["firebase"]);
app.controller("MyCtrl", ["$scope", "$firebaseArray", "$firebaseObject",
function($scope, $firebaseArray,$firebaseObject) {
var ref = firebase.database().ref("Products/");
var list = $firebaseArray(ref);
$scope.list = list;
$scope.activeTabs = [];
// check if the tab is active
$scope.isOpenTab = function (tab) {
// check if this tab is already in the activeTabs array
if ($scope.activeTabs.indexOf(tab) > -1) {
// if so, return true
return true;
} else {
// if not, return false
return false;
}
}
// function to 'open' a tab
$scope.openTab = function (tab) {
// check if tab is already open
if ($scope.isOpenTab(tab)) {
//if it is, remove it from the activeTabs array
$scope.activeTabs.splice($scope.activeTabs.indexOf(tab), 1);
} else {
// if it's not, add it!
$scope.activeTabs.push(tab);
}
}
}
]);
HTML Code
<div class="container accordion__container" ng-controller="MyCtrl">
<div class="accordion__tab" ng-repeat="products in list">
<div class="accordion__tab-title" ng-click="openTab(products.$id)">{{products.$id}} </div>
<div class="accordion__tab-content" ng-show="isOpenTab(products.$id)">
<div class="accordion__tab-contentdet" ng-repeat="productDet in <sub Product details>">
</div>
</div>
</div>
</div>
I made some changes in your code.
In HTML i used nav tabs.
<ul class="nav nav-tabs">
<li ng-repeat="products in list">
<a data-toggle="tab" href="#{{products.id}}">{{products.id}}</a>
</li>
</ul>
<div class="tab-content">
<div id="{{products.id}}" class="tab-pane fade" ng-repeat="products in list">
<h3>{{products.id}}</h3>
<p>Content : {{products.data}}.</p>
</div>
</div>
Controller
app.controller("MyCtrl", ["$scope", "$firebaseObject",
function($scope, $firebaseObject) {
var ref = firebase.database().ref("Products");
var list = $firebaseObject(ref);
list.$loaded().then(function() {
$scope.list = [];
angular.forEach(list, function(value,key){
$scope.list.push({ id: key, data: value})
})
});
}
]);
Another Method
Instead of using list.$loaded() you can use the below code:
ref.once('value', function(snapshot) {
$scope.list = [];
angular.forEach(snapshot.val(), function(value,key){
$scope.list.push({ id: key, data: value})
})
})
I just created a plunker for you. Please check it
https://plnkr.co/edit/5dOr7xAWIFlmdykAC1yh
if you have any doubt please let me know.

Firebase & Angular - Retrieve and display flattening data

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>

Retrieve specific data within ng-repeat loop angularjs

I'd like to retrieve specific data within a JSON file within an ng-repeat loop, My code is as follows thus far, and it works correctly bringing in the correct low resolution url of the image. I want to display the first comment corresponding to this image from a specific user below it in the <p> tag, ie I want the the first "text" value always from the username "tellasaur". Not sure how to bring that in, could I have some help? thanks!
NG-REPEAT LOOP
<li ng-repeat="p in pics">
<img ng-src="{{p.images.low_resolution.url}}" />
<p></p>
</li>
CONTROLLER
app.controller('ShowImages', function($scope, InstagramAPI){
$scope.layout = 'grid';
$scope.data = {};
$scope.pics = [];
InstagramAPI.fetchPhotos(function(data){
$scope.pics = data;
console.log(data)
});
});
JSON
"images":{
"low_resolution":{
"url":"https:\/\/scontent.cdninstagram.com\/hphotos-xaf1\/t51.2885-15\/s320x320\/e15\/11243658_841091872640638_1858051687_n.jpg",
"width":320,
"height":320
},
},
"comments":{
"count":38,
"data":[
{
"created_time":"1436314585",
"text":"Living on a lake #amarie4107",
"from":{
"username":"tellasaur",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/11142181_1606991566225969_1204610350_a.jpg",
"id":"174270894",
"full_name":"kristella"
},
"id":"1024203434844916571"
},
{
"created_time":"1436317671",
"text":"Wow",
"from":{
"username":"sbcarol2002",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/10707061_359756607505353_826681437_a.jpg",
"id":"1280059782",
"full_name":"Susan Long"
},
"id":"1024229322726738700"
},
{
"created_time":"1436320519",
"text":"\ud83d\udc93 dreamyy",
"from":{
"username":"veekster",
"profile_picture":"https:\/\/igcdn-photos-h-a.akamaihd.net\/hphotos-ak-xtf1\/t51.2885-19\/11117059_1743047859255223_204225114_a.jpg",
"id":"31179150",
"full_name":"Victoria Wright"
},
"id":"1024253210688915485"
}
]
}
Here's one way to do it using a filter.
angular.module('app',[])
.filter('getFirstCommentFrom',function(){
return function(arr, user){
for(var i=0;i<arr.length;i++)
{
if(arr[i].from.username==user)
return arr[i].text;
}
return '';
}
})
.controller('TestCtrl', function($scope){
$scope.pics = [
{ "images":{
"low_resolution":{
"url":"https:\/\/scontent.cdninstagram.com\/hphotos-xaf1\/t51.2885-15\/s320x320\/e15\/11243658_841091872640638_1858051687_n.jpg",
"width":320,
"height":320
},
},
"comments":{
"count":38,
"data":[
{
"created_time":"1436314585",
"text":"Living on a lake #amarie4107",
"from":{
"username":"tellasaur",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/11142181_1606991566225969_1204610350_a.jpg",
"id":"174270894",
"full_name":"kristella"
},
"id":"1024203434844916571"
},
{
"created_time":"1436317671",
"text":"Wow",
"from":{
"username":"sbcarol2002",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/10707061_359756607505353_826681437_a.jpg",
"id":"1280059782",
"full_name":"Susan Long"
},
"id":"1024229322726738700"
},
{
"created_time":"1436320519",
"text":"\ud83d\udc93 dreamyy",
"from":{
"username":"veekster",
"profile_picture":"https:\/\/igcdn-photos-h-a.akamaihd.net\/hphotos-ak-xtf1\/t51.2885-19\/11117059_1743047859255223_204225114_a.jpg",
"id":"31179150",
"full_name":"Victoria Wright"
},
"id":"1024253210688915485"
}
]
}
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app" ng-controller="TestCtrl">
<li ng-repeat="p in pics">
<img ng-src="{{p.images.low_resolution.url}}" />
{{p.comments.data|getFirstCommentFrom:'tellasaur'}}
<p></p>
</li>
</div>

angularjs ng-repeat filter on static value not working

I can't figure out why the code below is not filtering just the values with unique_id of "027". I've tried it as a string as well '027'...
JSON file:
[
{
"unique_id":"027",
"title":"How Speed Relates to Energy",
"state":"NY",
"state_id":"1.S2.3a"
}
]
Here my controller:
var abApp = angular.module('abApp', []);
abApp.factory('abData', function($http, $q) {
var deffered = $q.defer();
var data = [];
var abData = {};
abData.async = function() {
$http.get('/data/ab_activities.json')
.success(function(ab) {
data = ab;
deffered.resolve();
});
return deffered.promise;
};
abData.data = function() {
return data;
};
return abData;
});
abApp.controller("abEE", function(abData, $scope) {
var abApp = this;
abData.async().then(function(ab) {
abApp.alignments = abData.data();
});
})
Here's my HTML:
<div ng-controller="abEE as ee">
<ul>
<li ng-repeat="align in ee.alignments | filter:{unique_id : 027} ">
{{align.unique_id}} - {{align.state}}, {{align.state_id}}
</li>
</ul>
</div>
you need to correct your html markup like this, as in your JSON unique_id is a string:
<div ng-controller="abEE as ee">
<ul>
<li ng-repeat="align in ee.alignments | filter:{unique_id : '027'} ">
{{align.unique_id}} - {{align.state}}, {{align.state_id}}
</li>
</ul>

Resources