I'm using Ionic Creator and when I export the project, it doesn't have any .ts file. I have issue trying to get ngFor working for my code.
I'm using the $scope variable to pass array object from the Controller to the Template.
grocery.html (/template)
<ion-list id="groceriesHistory-list4">
<ion-item class="item-icon-right" id="groceries-list-item13" ng-repeat="grocery in groceries">{{ grocery.date }}
<span class="item-note">Free 1.5L Drink Redeemed</span>
<i class="icon ion-android-bar"></i>
</ion-item>
groceryCtrl
firebase.database().ref("table").orderByChild("user").equalTo("userid").on("value", function(snapshot) {
var credit = 0;
var groceryHistory = [];
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
//console.log(childData);
if(childData.type == 1) {
if(childData.used == 1) {
groceryHistory.push(childData);
}
}
});
console.log(groceryHistory);
$scope.groceries = groceryHistory;
There is no data to display even though $scope.groceries contain at least an object.
Edit1: I edited my code for angularjs v1 but there is still no data to display.
Edit2: It is working but I have to click the sidemenu first before the data display itself.
ng-for does not exists in angularjs. You need to use ng-repeat:
<ion-list id="groceriesHistory-list4">
<ion-item class="item-icon-right" id="groceries-list-item13" ng-repeat="grocery in groceries">{{ grocery.date }}
<span class="item-note">Free 1.5L Drink Redeemed</span>
<i class="icon ion-android-bar"></i>
</ion-item>
Based on your update2, your scope changes is not in a angular digest cycle. Simply put your changes in a $timeout to make sure a digest cycle will run:
$timeout(function(){
$scope.groceries = groceryHistory;
})
Related
I am working on a web app where non-profit organizations can create a profile and be easily searchable by various parameters. In the "create and organization" form, I have a nested array where the organization can add donations that they need. The array is storing ok (I can add multiple donations), however when I try to display it using ng-repeat, nothing renders. When I don't use the ng-repeat and just display via {{ ctrl.organization.donations }} the information shows up with brackets and quotation marks.
Here is the code that I use to add the donations (via the newOrganization controller):
function NewOrganizationController(OrganizationService, CategoryService, $stateParams, $state, $http, Auth){
var ctrl = this;
CategoryService.getCategories().then(function(resp) {
ctrl.categories = resp.data;
});
ctrl.donations = [{text: ''}];
Auth.currentUser().then(function(user) {
ctrl.user = user;
})
ctrl.addNewDonation = function() {
var newDonation = ctrl.donations.length+1;
ctrl.donations.push({text: ''});
};
ctrl.removeDonation = function() {
var lastItem = ctrl.donations.length-1;
ctrl.donations.splice(lastItem);
};
ctrl.addOrganization = function() {
var donations = this.donations;
var allDonations = [];
for (var key in donations) {
if (donations.hasOwnProperty(key)) {
var donation = donations[key].text;
allDonations.push(donation);
}
}
var data = {
name: ctrl.organization.name,
description: ctrl.organization.description,
address: ctrl.organization.address,
donations: allDonations.join("/r/n"),
category_id: this.category.id
};
OrganizationService.createOrganization(data);
$state.go('home.organizations');
};
}
angular
.module('app')
.controller('NewOrganizationController', NewOrganizationController);
Here is the code that I am using to display the array on my show page (this is what shows up with brackets, i.e. donations needed: ["food", "clothing"]):
<h5>{{ ctrl.organization.donations }}</h5>
This is the ng-repeat code that is not rendering anything to the page:
<li class="list-group-item" ng-repeat="donation in donations track by $index">
{{ donation }}
</li>
I've tried to use .join(', ') within the {{donation}} brackets, but this isn't recognized as a function.
edit: After taking AJ's suggestion here is a screenshot of what appears...anyone know how to fix this?
seems that my array is showing up in table form, with each row containing one character
Any help would be greatly appreciated. Here is a link to the github repo in case you want to look at anything else or get a bigger picture.
You need to use the same variable name that works in the h5
<li class="list-group-item" ng-repeat="donation in ctrl.organization.donations track by $index">
{{ donation }}
</li>
I have a code structure where I ready the stores that works perfectly. However, I need to list promotions that are in each store and each promotion has a unique id so I would like to know how to list all the promotions that are inside every store follow the code:
in app.js
app.factory('Promos', function($firebaseArray){
var ref = new Firebase('https://myapp.firebaseio.com/');
var refPromoArray = $firebaseArray(ref);
return{
getPromos: function() {
if (refPromoArray) {
return $firebaseArray(ref.child('promotions'));
}
}
})
in controller.js
.controller('PromoListCtrl', function($scope, $state, $stateParams, $ionicLoading, Promos) {
$scope.promoslist = Promos.getPromos();
console.log($scope.promoslist);
})
in promo_list.html
<ion-list ng-if="promoslist.length > 0" can-swipe="true">
<ion-item ng-repeat="promoslist in promo" type="item-text-wrap"
href="#/app/local/{{promo.$id}}">
<img ng-src="{{promo.photo}}" />
{{local.title}}
</ion-item>
</ion-list>
Result
How about something like this:
var ref = firebase.database().ref('/promotions/');
ref.on('value', function(snapshot) {
snapshot.forEach(function(data) {
console.log(data.key + " = " + data.val().yourpoerty);
});
Actually the snapshot is your array. If you want some sort of a normal array only with data, you can create one and add them manually in an array. Good luck.
Hello thank you for the answer your code worked to group the promotions, but now I have another problem, to list I changed the code to create an array with all the promotions as follows:
my code:
var promoslist = [];
promos = ref.child('promotions');
promos.on('value', function(snapshot) {
snapshot.forEach(function(data) {
promoslist.push(data.val());
});
});
**To list via the code below:**
<ion-list ng-if="promoslist.length > 0">
<Ion-item ng-repeat = "promo in promoslist">
{{Promo}}
</ Ion-item>
</ion-list>
In this case I have 2 stores with 4 promotions but the code is generating an array of two dimensions with the two promotions of each item so ng-repeat only runs twice showing only the results if I change the list to an index ex:
Promoslist [0] or promoslist 1
<Ion-item ng-repeat = "promo in promoslist[0]">
I would like to just create an array of one dimension with all the promotions to list them all at once how do I create a simple array with all?
Follows the image of the result:
Resuult
I found the solution doing a loop-repeat combination in ng-repeat as following code:
<ion-list ng-if="promoslist.length > 0" can-swipe="true" >
<div ng-repeat="promo in promoslist[0]">
<ion-item ng-repeat="promo in promoslist[$index]" type="item-text-wrap" class="item-avatar"
href="#/app/promo/{{promo.idstore}}/{{promo.id}}" ng-if="promo.status==='active'">
<img ng-src="{{promo.image}}"/>
{{promo.title}}
<p>{{promo.store}}</p>
</ion-item>
</div>
</ion-list>
I want to create a favorite list in my application based on user selection. In my app, I use a long JSON file with a bunch of text which is loaded with $http.get().
This is code for displaying content in my view.
<ion-view>
<ion-nav-title></ion-nav-title>
<ion-content>
<div class="card" ng-repeat="list in items | filter: { id: whichid }">
<div class="item item-text-wrap"
ng-repeat="item in list.content | filter: { id2: whichid2 }"
ng-bind-html="item.description.join('')">
<h3>{{ item.name }}</h3>
<p>{{ item.description }}</p>
</div>
</div>
</ion-content>
The basic idea for creating a favorite list is to save displayed text in the array. After that, I can easily print that array in a template for the favorite list.
So the problem is how I can save text/data form expression ({{ item.name }}, {{ item.description }}) to the array? Or if anyone has some other idea for making that favorite list.
Pass the item details to a function defined in your controller using ng-click and push it into an array as shown below :
<ion-view>
<ion-nav-title></ion-nav-title>
<ion-content>
<div class="card" ng-repeat="list in items | filter: { id: whichid }">
<div class="item item-text-wrap" ng-click="favouriteThis(item)"
ng-repeat="item in list.content | filter: { id2: whichid2 }"
ng-bind-html="item.description.join('')">
<h3>{{ item.name }}</h3>
<p>{{ item.description }}</p>
</div>
</div>
</ion-content>
In your controller :
Write the "favouriteThis" function to push the favourited item every time the user clicks on it :
$scope.favouriteList = [];
$scope.favouriteThis = function (item) {
$scope.favouriteList.push(item); // make sure to check for duplicates before pushing the item, the logic for which i've not included here.
}
As you have all the favourited item details in the "$scope.favouriteList", you can use that information in your favourite list directly. To make it more accurate, while checking for duplicates you can also record the number of times user interacted with a particular item using which you can show the most interacted item on the top of the list.
Hope this helps :)
I would suggest creating a service/controller for this approach since you are making http calls which return JSON objects (use a service, as well as a controller). In the service have your functions such as getFavorites, addToFavorites, deleteFromFavorites etc. These functions will http GET/POST/UPDATE on your favorites list. Then you will want to return the JSON object to a controller. In the controller you'll have control over the scope and set scope variables to display the data in your app.
Here is a basic example:
Service
//****************
//Favorite Factory
//****************
.factory('favoriteFactory', function ($http) {
var favFac = {};
var favorites = [];
favFac.getFavorites = function (userId) {
//$http.get() call to get specific user's favs
};
favFac.addToFavorites = function (name, description) {
//$http.post() call to post to a users favs
};
favFac.deleteFromFavorites = function(userId, itemId) {
//$http.update() call to delete item from users favs
}
return favFac;
});
Controller
//Favorite Controller
.controller('FavoritesCtrl', ['$scope', '$stateParams', 'favoriteFactory', function ($scope, $stateParams, favoriteFactory) {
//Route current user Id to controller. Pass to service to look up their favorites in db
var userId = $stateParams.id;
$scope.favorites = favoriteFactory.getFavorites(userId);
$scope.addToFavorites = function(name, description){
favoriteFactory.addToFavorites(name, description);
}
}])
HTML
<ion-view view-title="Favorites Page" ng-controller="FavoritesCtrl">
<ion-content>
<ion-item collection-repeat="favorite in favorites">
<h3>{{ favorite.name }}</h3>
<p>{{ favorite.description }}</p>
<button type="button" ng-click="addToFavorites(favorite.name, favorite.description)">Add</button>
</ion-item>
</ion-content>
I'm working on a project where user can like comment made by users. and what i want to achieve is when a user likes a comment on a page by default + 1 should be added to the total comments made. Below is my script my it doesn't work
.controller('feedsctrl',['$scope','$http',function($scope,$http){
$http.get('http://localhost/vivalooks/app_ion/like.php').success(function(data){
//$scope.feeds = console.log(data) ;
$scope.feeds = data;
$scope.lovepic = function() {
event.preventDefault();
$http.post("http://localhost/vivalooks/app_ion/scripts/comment.php",
{
'u_pic_id': $scope.u_pic_id,
'pic': $scope.pic
}
).success(function(data,status,headers,config){
console.log(data)
$scope.comment_total=$scope.comment_total+1;
});
}
});
}])
HTML
<ion-content>
<div ng-controller="feedsctrl" class="list card has-subheader" ng-repeat="item in feeds">
{{item.comment_total}} Comments
</ion-content>
Issue with your code is that you are trying to update the $scope.data[item].comments with $scope.comments. These both are different variable in angular controller scope. you should perform the addition in the same scope variable to get it reflected on the view. You can achieve this by slight modification in your code
html
<ion-content>
<div ng-controller="feedsctrl" class="list card has-subheader" ng- repeat="item in feeds trach by $index">
<img src="item.src" ng-click="lovepic($index)">
{{item.comment_total}} Comments
</div>
</ion-content>
in the controller.
$scope.lovepic=function(index) {
event.preventDefault();
$http.post("http://localhost/vivalooks/app_ion/scripts/comment.php",
{'u_pic_id':$scope.feeds[index].u_pic_id,'pic':$scope.feeds[index].pic})
.then(function(data,status,headers,config){
$scope.feeds[index].comment_total == undefined ? 1 : $scope.feeds[index].comment_total +1;
});
}
I have a very big list which is an array named leagues, I need to allow the user to take the elements on that array(list) , and choose those as favorites by clicking a button
$scope.favoriteLeagues = [];
$scope.favoriteLeague = function(league) {
$scope.favoriteLeagues.push(league);
}
so I want to know what am I doing wrong ? the function sometimes allows me to add one as favorite, but once I click on the second one, I got a message of something undefined, and also, the binding is not working, I am unable to see the {{favoriteLeagues.name}} printed.
UPDATED AS REQUESTED
<div>
<strong>Favorites</strong>
{{favoriteLeagues.name}}
</div>
<ion-option-button class="button-light icon ion-star"
on-tap="favoriteLeague(league)">
</ion-option-button>
<div ng-repeat="sport in sportsFilter = (sports | filter:query)">
<strong>{{sport.name}}</strong>
</div>
<ion-item ng-repeat="league in sport.leagues">
<div>{{league.name}}</div>
</ion-item>
</ion-list>
here the controller:
.controller('SportsController', function($scope, $state,
AuthFactory, SportsFactory) {
$scope.favoriteLeagues = [];
$scope.sports = [];
AuthFactory.getCustomer().then(function(customer) {
$scope.customer = customer;
SportsFactory.getSportsWithLeagues(customer).then(function(sports) {
if (sports.length) {
$scope.sports = sports;
}
$scope.isSportShown = function(sport) {
return $scope.shownSport === sport;
};
$scope.favoriteLeague = function(league) {
$scope.favoriteLeagues.push(league);
}
};
});
You haven't pasted the full html, but it should look something like this:
<!-- Use ng-app to auto-bootstrap an AngularJS application-->
<!-- Use ng-controller to attach your view with your SportsController controller -->
<ion-list>
<div>
<strong>Favorites</strong>
<!-- Looping through all the favourite leagues-->
<div ng-repeat="favouriteL in favoriteLeagues">
{{favouriteL.name}}
</div>
</div>
<!-- Looping through all the sports -->
<div ng-repeat="sport in sportsFilter = (sports | filter:query)">
<!-- Bind the sport name -->
<strong>{{sport.name}}</strong>
<!-- Looping through all the leagues -->
<ion-item ng-repeat="league in sport.leagues">
<!-- Display a button which on tap will call favoriteLeague function -->
<ion-option-button class="button-light icon ion-star" on-tap="favoriteLeague(league)">
</ion-option-button>
<!-- Bind the name of the league -->
<div>{{league.name}}</div>
</ion-item>
</div>
</ion-list>
Don't forget to attach the view with your controller using ng-controller.
I can't help you much with angular.js, I've never used it, but the fact that you are accidentally replacing the array with the function probably doesn't help. ng-repeat is trying to loop through favoriteLeagues but fails because that's a function! Look at the comments I put in your code.
$scope.favoriteLeague = []; // creates an array
$scope.favoriteLeague = function(league) { // replaces the array with a function!!!
$scope.favoriteLeagues.push(league); // suddenly leagues takes an S ?
}
To avoid this type of error, you should respect a naming convention for your functions. I like to use action words and verbs for functions. I only use plural forms on arrays and related functions. Here's what I'd do in your case:
$scope.favoriteLeagues = [];
$scope.addToFavoriteLeagues = function(league) {
$scope.favoriteLeagues.push(league);
}
You need to attach your controller to the html in order for the bind to work, usually at the top level parent element, e.g a div, containing the ngrepeat markup.