How to show ionic popup using ng-click inside ng-repeat - javascript

here's my html code.
<div class='list' ng-repeat='worker in categories' >
<br><a class="item item-thumbnail-left" ng-click="showConfirm(worker.$id)">
<img src="img/tech_support.png">
<p>{{worker.$id}}</p>
<p>Address: {{worker.Address}}</p>
<p><u>more..</u></p>
</a>
</div>
and here's my controller.js
man.controller('categoryCtrl',function($scope,$firebaseArray,
$firebaseObject,$state,$stateParams,$ionicPopup,$window,$timeout){
var category = $stateParams.categoryId;
var categoryRef = Refroot.child('Workers').child(category);
$scope.categories=$firebaseArray(categoryRef);
$scope.showConfirm= function(id){
var workerId = id;
var workRef = Refroot.child('Workers');
var lastRef = workRef.child(category).child(workerId);
$scope.workerlist = $firebaseArray(lastRef);
var confirmPopup = $ionicPopup.confirm({
title: 'Worker Profile',
});
confirmPopup.then(function(res) {
if(res) {
console.log('Sure!');
} else {
console.log('Not sure!');
}
});
console.log(workerId + '' + category + '' + lastRef);
}
});
Hope you guys could help me, it will be a great help for my thesis :)

You should be using $index as below
<div class='list' ng-repeat='worker in categories track by $index' >
<br><a class="item item-thumbnail-left" ng-click="showConfirm($index)">
<img src="img/tech_support.png">
<p>{{$index}}</p>
<p>Address: {{worker.Address}}</p>
<p><u>more..</u></p>
</a>
</div>

Related

Remove specific data from firebase using Angularjs

I'm trying to remove specific data from firebase using angularjs. But my coding removes all data from it. Any Help would be Appreciated.
For Example i need to delete the second data as highlighted using the remove button in it.
My HTML:
<div class="container" ng-controller="budgetCtrl">
<div class="row list" ng-repeat="kasu in panam">
<div class="col-6"> {{ kasu.title }} </div>
<div class="col-6 text-right total">
{{ kasu.spent | currency:"₹" }}
<button type="button" ng-click="deleteSpent(panam)">Remove</button>
</div>
</div>
<div class="row" style="background: #1feb6b">
<div class="col-6"> Total Money spend </div>
<div class="col-6 text-right"> {{ getTotal() | currency:"₹" }} </div>
</div>
</div>
My JS:
var nombre = angular.module('nombre', ['ngRoute', 'firebase']);
nombre.controller('budgetCtrl', ['$scope', 'money', '$firebaseObject', function($scope, money, $firebaseObject){
money.then(function(data){
$scope.cash = data;
});
var ref = firebase.database().ref();
$scope.panam = $firebaseObject(ref);
$("#nombre").submit(function() {
if( (!$("#Spentfor").val()) || (!$("#SpentAmount").val()) ) {
$(".form-control").css({"border":"3px solid red"});
}
else {
$(this), console.log("Submit to Firebase");
var Spentfor = $("#Spentfor").val(),
SpentAmount = $("#SpentAmount").val(),
total = { title: Spentfor, spent: SpentAmount};
return ref.push().set(total).then(function() {
$("#Spentfor, #SpentAmount").val("");
});
}
});
$scope.getTotal = function(){
var total = 0;
$scope.panam.forEach(p => {
total += parseFloat(p.spent);
});
return total;
}
$scope.deleteSpent = function(info){
$scope.panam
.$remove(info)
.then( function(ref){}, function(error){})
}
}]);
On Above JS i'm trying to delete specific data in firebase using deleteSpent() function. I know that i'm missing to targeting the specific data in my JS. If somebody helps me to solve and understand its concept would be appreciated.

How to keep track if a button has been clicked already?

I am writing an app with Ionic and Firebase and my users have the choice to add something to their "Favorites".
Now, I found a way to have the user clicking the button and changing the text once clicked and saving the data in the database, but if the user moves to another page and come back, the button comes back to "Add to favorites".
How to display the text on the button regarding what the user did with it before ?
The DOM :
<div class="list card" id="topLetters-card21" ng-repeat="letter in letters">
<ion-item class="item-avatar item-icon-right" id="userId{{$index}}" alt="{{letter.uid}}" ui-sref="menu.user">
<img src="{{letter.userpic}}" alt="">
<h2>{{letter.username}} </h2>
<p>{{letter.location}}</p>
<i class="icon ion-android-arrow-dropright"></i>
</ion-item>
<h2 style="color:#000000;" class="padding-left" id="letterId{{$index}}" alt="{{letter.letter}}">{{letter.title}}</h2>
<div style="{{letter.font}}background: url(img/{{letter.background}}.jpg) no-repeat center;background-size:cover;">
<h5 style="{{letter.font}}text-align:right;"id="topLetters-heading15" style="color:#000000;" class="padding">{{letter.date}}</h5>
<h5 style="{{letter.font}}"id="topLetters-heading4" style="color:#000000;" class="padding">{{letter.opening}} {{letter.to}}, </h5>
<div id="topLetters-markdown3" style="text-align:justify;" class="show-list-numbers-and-dots padding">
<p style="color:#000000;">{{letter.message}}</p>
</div>
<h5 style="{{letter.font}}"id="topLetters-heading5" style="color:#000000;text-align:right;" class="padding">{{letter.conclusion}}, {{letter.username}}.</h5>
</div>
<button id="addletter{{$index}}" ng-click="addToFavorites($index)" class="button button-dark button-small button-block icon ion-ios-heart-outline" alt={{letter.letter}}> Add to Favorites</button>
<ion-item class="item-icon-left item-icon-right" id="topLetters-list-item29">
<i class="icon ion-ios-heart-outline"></i>{{letter.likes}}
<i class="icon ion-ios-flag"></i>
</ion-item>
<div class="spacer" style="width: 300px; height: 29px;"></div>
</div>
The Controller :
var ref = firebase.database().ref('/letters');
//retrieve the items in the cart of the user
ref.orderByChild("likes").on("value", function(snapshot1) {
$timeout(function(){
$scope.letters = snapshot1.val();
})
})
$scope.addToFavorites = function(ind){
var letterId = document.getElementById('letterId'+ind).getAttribute('alt');
var userId2 = document.getElementById('userId'+ind).getAttribute('alt');
var userId = firebase.auth().currentUser.uid;
//Add the letterUid and ID to our favorites to retrieve it later
//Add our uid to the letter to count the number of Favorites
if(document.getElementById('addletter'+ind).textContent == " Add to Favorites"){
$timeout(function(){
firebase.database().ref('accounts/' + userId + '/favorites/' + letterId).update({
letterId: letterId,
userId: userId2,
});
firebase.database().ref('letters/' + letterId + '/favorites/' + userId).update({
userId: userId,
});
document.getElementById('addletter'+ind).textContent = " Remove from Favorites";
})
} else if (document.getElementById('addletter'+ind).textContent == " Remove from Favorites")
$timeout(function(){
document.getElementById('addletter'+ind).textContent = " Add to Favorites";
firebase.database().ref('/accounts/' + userId + "/favorites/" + letterId).remove();
firebase.database().ref('/letters/' + letterId + "/favorites/" + userId).remove();
})
}
I believe you should do something like this:
JS
$scope.accountsFavorites = [];
$scope.lettersFavorites = [];
$scope.getFavorites = function(){
$scope.accountsFavorites = firebase.database().ref('/accounts/' + userId + "/favorites/")
$scope.lettersFavorites = firebase.database().ref('/letters/' + letterId + "/favorites/")
$scope.syncFavorites();
}
$scope.syncFavorites() {
$scope.letters.forEach(function(letter){
$scope.lettersFavorites.forEach(function(favoriteLetter){
if(letter.id == favoriteLetter.letter_id) { // or something
letter.isFavorite = true;
}
})
})
}
$scope.getFavorites();
HTML
<button
id="addletter{{$index}}"
ng-click="addToFavorites($index)"
class="button button-dark button-small button-block icon ion-ios-heart-outline"
alt={{letter.letter}}>
<span data-ng-if="letter.isFavorite">Remove from favorites</span>
<span data-ng-if="!letter.isFavorite">Add to favorites</span>
</button>

Angular hide an element in ng-repeat on click

I have articles listed on a page in my app, where I have an iframe and overlay over that iframe. I want to have it that when a user clicks on an iframe overlay, that the title from that article gets hidden. Not sure how to achieve that in ng-repeat. This the code, where as of now, on a click event titles of all articles get hidden.
<ion-item ng-repeat="article in articles" class="item-light">
<div class="article">
<a ng-show="article.external_media.length == 0 || article.external_media.url == ''" href="#/main/article/{{article.id}}" nav-direction="forward" class="article-image-link">
<img src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<div class="iframe" ng-show="article.external_media.length > 0 && article.external_media.url != ''">
<iframe ng-src="{{article.external_media[0].url | safeUrl }} "></iframe>
<div class="article-image-link">
<h1 ng-hide="videoPlaying">{{ article.title.split(' ', 7).join(' ') }}</h1>
</div>
<div class="iframe-overlay" ng-click="playVideo()"></div>
</div>
</div>
</ion-item>
Controller:
$scope.playVideo = function(videoSrc) {
$scope.videoPlaying = true;
$scope.videoSrc = videoSrc + "&autoplay=1";
};
you can also use $index for this purpose.
controller
app.controller('someController',function($scope){
$scope.videoPlaying = [];
$scope.playVideo = function(videoSrc,index) {
$scope.videoPlaying[index] = true;
$scope.videoSrc = videoSrc + "&autoplay=1";
};
$scope.stopVideo = function(videoSrc,index) {
$scope.videoPlaying[index] = false;
$scope.videoSrc = videoSrc + "&autoplay=1";
};
})
HTML
i am changing only two lines rest are same as it is
<h1 ng-hide="videoPlaying[$index]">{{ article.title.split(' ', 7).join(' ') }}</h1>
<div class="iframe-overlay" ng-click="playVideo($index)"></div>
I've created a JSFIDDLE (basic) to give you a head start on what you are trying to do.
VIEW
<div ng-app="app">
<div ng-controller="helloCnt">
<div ng-repeat='item in data'>
<span ng-if="item.hide === undefined || !item.hide">{{item.name}}</span>
<div ng-if="!item.hide" ng-click="playVideo(item)">
HIDE
</div>
<div ng-if="item.hide" ng-click="stopVideo(item)">
SHOW
</div>
<br/>
</div>
</div>
</div>
CONTROLLER
var app = angular.module('app', [])
app.controller('helloCnt', function($scope) {
$scope.data = [{
'name': 'test'
}, {
'name': 'in'
}, {
'name': 'dummy'
}, {
'name': 'data'
}]
$scope.playVideo = function(item, videoSrc) {
// other code
item.hide = true;
};
$scope.stopVideo = function(item, videoSrc) {
// other code
item.hide = false;
};
})
SEE JSFIDDLE

Make modification and decide where to put an element before his creation - using angularjs with directives

I'm trying to detect the creation of an element (an new added element) and do an action on this element (modification) and decide where to put it.
The element is added by an anguler biding items and I use a new directive:
My page HTML:
<body ng-controller="MainCtrl">
<main style="overflow: hidden;">
<input type="text" ng-model="url" ng-keyup="$event.keyCode == 13 ? addItem(url) : null" class="form-control" id="myinputurl" autofocus="autofocus" autocomplete="on" placeholder="Type URL">
<section class="cd-section index cd-selected">
<p>My section</p>
<content-item ng-repeat="item in items" itemActive="{{item.active}}" type="section"></content-item>
</section>
<!-- section -->
</main>
<nav class="cd-nav-container" id="cd-nav">
<p>My list</p>
<ul class="cd-nav">
<content-item ng-repeat="item in items" itemActive="{{item.active}}" type="list"></content-item>
</ul>
<!-- nav -->
</nav>
</body>
Add the item in a items scope:
$scope.addItem = function(myurl) {
var lastChildId = $("ul li").length;
var vall = lastChildId + 1;
var idItem = "item" + vall;
angular.forEach($scope.items, function(p) {
p.active = false; //set them all to false
});
//var trustedUrl = trustSrc(myurl);
$scope.items.push({
id: idItem,
item: '<a id="' + idItem + '" href="' + myurl + '"> Test for StackOverFlow </a>',
active: true
});
}
My directive:
app.directive('contentItem', function() {
return {
restrict: "EA",
scope: false,
template: function(elem, attr) {
var template = 'ErrorFail';
var type = attr.type;
if (type === "section") {
if (attr.itemActive) {
template = '{{item.itemm}}';
}
} else {
template = '<li id="{{item.id}}" color="red">{{item.itemm}}</li>';
}
return template;
}
}
});
Can someone help me please ?? This is Plunker Link

AngularJS not filtering products list

I am having an issue with AngularJS filtering my products list. I have done a few console.log queries on my variables and all seem fine. The problem is that the view does not update to show the filtered products.
Filtering works perfectly fine when you enter the search text in the input box but it does not work when clicking on the Category menu items.
I would like to filter the product list by category when the user clicks on the menu item.
Please see my code below and any help or advice is greatly appreciated.
My app.js
myApp.controller('StoreController', function($scope, $filter, storeFactory, cartFactory) {
$scope.cartTotal = 0;
$scope.cartItems = [];
$scope.categories = [];
$scope.counted = 0;
$scope.filteredProducts = {};
//get the products
storeFactory.getProducts(function(results) {
$scope.products = results.products;
$scope.counted = $scope.products.length;
$scope.filteredProducts = results.products;
});
$scope.$watch("search", function(query){
if($scope.filteredProducts.length) {
$scope.filteredProducts = $filter("filter")($scope.products, query);
$scope.counted = $scope.filteredProducts.length;
}
});
$scope.filterProductsByCategory = function(categoryName){
console.log('category filter');
/*$scope.products.forEach(function(o,i){
console.log('filter');
if( o.category_id !== categoryId ){
$scope.filteredProducts.splice(i,1);
console.log('removing');
console.log(o);
}
});*/
$scope.filteredProducts = $filter("filter")($scope.filteredProducts, categoryName);
console.info('the filtered items');
console.log($scope.filteredProducts);
$scope.counted = $scope.filteredProducts.length;
}
$scope.getCategories = function(){
storeFactory.getCategories(function(results){
$scope.categories = results.rows;
});
}
$scope.getCategories();
});
My store.htm
UPDATE :
I removed the extra controller reference and wrapped everything in one div.
<div ng-controller="StoreController">
<!-- the sidebar product menu -->
<div class="block-content collapse in">
<div class="daily" ng-repeat="category in categories | orderBy:'name'">
<div class="accordion-group">
<div ng-click="filterProductsByCategory(category.category_name)" class="accordion-toggle collapsed">{{category.category_name}}</div>
</div>
</div>
</div>
</div>
<!-- Load store items start -->
<div class="label">Showing {{counted}} Product(s)</div>
<div class="row" ng-repeat="product in filteredProducts | orderBy:'product_name'" style="margin-left: 0px; width: 550px;">
<hr></hr>
<div class="span1" style="width: 120px;">
<!-- <a data-toggle="lightbox" href="#carouselLightBox"> -->
<a data-toggle="lightbox" href="#carouselLightBox{{product.product_id}}">
<!--img alt={{ product.product_name }} ng-src="{{product.image}}" src="{{product.image}}" /-->
<img id="tmp" class="" src="images/products/{{product.product_image_filename}}" alt=""></img>
</a>
<div class="lightbox hide fade" id="carouselLightBox{{product.product_id}}" style="display: none;">
<div class='lightbox-content'>
<img src="images/products/{{product.product_image_filename}}" alt="" />
<!--img alt={{ product.product_name }} ng-src="{{product.image}}" src="{{product.image}}" /-->
<button class="btn btn-primary" id="close_lightbox" ng-click="closeBox(product.product_id, $event)">Close</button>
</div>
<style>
#close_lightbox
{
position: absolute;
top: 5px;
right: 5px;
}
</style>
</div>
</div>
<div class="span6" style="width: 330px; margin-bottom: 15px;">
<h5 style="font-size: 14px; font-weight: bold;">{{product.product_name}}</h5>
<p>{{product.product_description }}</p>
<p>Category : {{product.category_name}}</p>
</div>
<div class="span3">
<p class="price">Price : <strong>R{{ product.product_price }}</strong></p>
</div>
</div>
<!-- end of controller -->
</div>
$scope.filteredProducts = {};
//get the products
storeFactory.getProducts(function (results) {
$scope.products = results.products;
$scope.counted = $scope.products.length;
$scope.filteredProducts = results.products;
});
Is results.products an array of objects or an object of objects? Because $filter('filter')($scope.products,query); expects $scope.products to be an array.
$scope.$watch("search", function (query) {
if($scope.filteredProducts.length) {
$scope.filteredProducts = $filter("filter")($scope.products, query);
$scope.counted = $scope.filteredProducts.length;
}
});
Here's what I'm thinking this should look like and you won't need the $watch statement or the filteredProducts array/object, In controller:
$scope.search = '';
$scope.products = [];
$scope.categories = ['category1','category2','category3'];
// assuming that your store function getProducts returns a promise here
storeFactory.getProducts().then(function(results){
$scope.products = results.products; // needs to be an array of product objects
});
$scope.filterProductsByCategory = function(category){
$scope.search = category;
};
Then in your HTML Partial, this is not exactly how your's is, I'm just showing you here in shorter form what is possible:
<button ng-repeat="cat in categories" ng-click="filterProductsByCategory(cat)">{{cat}}</button>
<div class="row" ng-repeat="product in products | filter:search | orderBy:'product_name'">
<!-- Product Information Here -->
</div>
I created a JSFiddle to demonstrate: http://jsfiddle.net/mikeeconroy/QL28C/1/
You can free form search with any term or click a button for a category.
The side bar is using one instance of StoreController, and the main div is using another instance of StoreController. Each instance having its own scope. The should both use the same controller instance: wrap everything inside a div, and use a unique StoreController for this wrapping div.

Categories