AngularJS & JSON - Obtain Value from Previous & Next Object - javascript

Background:
I have created an AngularJS test app which, obtains data from a JSON file, which is separated into categories and within each category is an employee card which is displayed through ng-repeat. These categories can then be viewed utilising a slider (using bxSlider).
Aim:
With bxSlider you can use custom Next/Previous buttons, what I wanted to achieve was to dynamically display the relevant category names in the Next/Previous buttons (please see annotation link below - my level does not allow me to post images).
Website Category Slider Wireframe
For example: the current category on view is the 'Technology' department, the previous button may then show 'Motors' department and the next button may show 'Law' department.
I understand that the code below would allow me to access the Category name 'Technology'. However this needs to be done in a dynamic nature.
{{employees[0].category}}
Below this I will include all what I believe to be relevant code.
JSON file:
[
{
"category": "Technology",
"shortname": "tech",
"icon": "fa-desktop",
"cards": [
{
"id": "card-1",
"name": "George Sofroniou",
"shortname": "G_Sof",
"age": "23",
"company": "Pirean Ltd.",
"role": "Graduate UI Developer"
},
{
"id": "card-2",
"name": "Steve Jobs",
"shortname": "S_Jobs",
"age": "56 (Died)",
"company": "Apple Inc.",
"role": "Former CEO"
},
{
"id": "card-3",
"name": "Mark Zuckerberg",
"shortname": "M_Zuck",
"age": "30",
"company": "Facebook",
"role": "CEO"
},
{
"id": "card-4",
"name": "Tim Cook",
"shortname": "T_Cook",
"age": "54",
"company": "Apple Inc.",
"role": "CEO"
},
{
"id": "card-5",
"name": "Jony Ive",
"shortname": "J_Ive",
"age": "48",
"company": "Apple Inc.",
"role": "Senior Vice President of Design"
},
{
"id": "card-6",
"name": "Marissa Mayer",
"shortname": "M_May",
"age": "39",
"company": "Yahoo!",
"role": "CEO"
},
{
"id": "card-7",
"name": "Yves Behar",
"shortname": "Y_Beh",
"age": "47",
"company": "Fuseproject",
"role": "Founder"
}
]
},
{
"category": "Motors",
"shortname": "mot",
"icon": "fa-car",
"cards": [
{
"name": "Elon Musk",
"shortname": "E_Musk",
"age": "43",
"company": "Tesla Motors",
"role": "CEO"
}
]
},
{
"category": "Football",
"shortname": "foot",
"icon": "fa-futbol-o",
"cards": [
{
"id": "card-1",
"name": "Sir Alex Ferguson",
"shortname": "A_Fer",
"age": "73",
"company": "N/A",
"role": "Retired"
}
]
},
{
"category": "Law",
"shortname": "law",
"icon": "fa-gavel",
"cards": [
{
"id": "card-1",
"name": "Harvey Specter",
"shortname": "H_Spec",
"age": "43",
"company": "Pearson Specter Litt",
"role": "Name Partner"
}
]
}
]
HTML Code:
<!-- Slider Container -->
<div class="slider-container">
<!-- Search Content -->
<!-- controls: true -->
<div class="content-results bxslider"
bx-slider="mode: 'horizontal', pager: true, nextSelector: '#next', prevSelector: '#prev', nextText: '<i class=\'fa fa-chevron-right\'></i>', prevText: '<i class=\'fa fa-chevron-left\'></i>', minSlides: 1, maxSlides:1, infiniteLoop: true, adaptiveHeight: true, hideControlOnEnd: false">
<!-- Employee -->
<div class="cards-container"
ng-repeat="item in filtered = ( employees | filter: query | orderBy:empOrder:direction )"
notify-repeat-finished>
<div class="category" ng-animate="'animate'" >
<div class="category-title">
<h1 class="title-cat"><i class="fa {{item.icon}}"></i> {{ item.category }}</h1>
</div>
<div class="category-cards-container">
<div class="employee-card card" ng-repeat="employee in filtered = (item.cards | filter: query | orderBy:empOrder:direction )" dom-manipulation>
<!-- Front Card -->
<div class="front">
<div class="pic-container">
<img ng-src="../static/images/placeholders/{{ employee.shortname }}.jpg" class="emp-pic" alt="Photo of {{ employee.name }}">
<h3 class="emp-name">{{ employee.name }}</h3>
<div class="darken"></div>
</div>
<ul class="emp-details">
<li class="detail emp-age">
<h5>Age: <small>{{ employee.age }}</small></h5>
</li>
<li class="detail emp-role">
<h5>Role: <br><small>{{ employee.role }}</small></h5>
</li>
<li class="detail emp-company">
<h5>Company: <br><small>{{ employee.company }}</small></h5>
</li>
</ul>
</div>
<!-- END Front Card -->
<!-- Back Card -->
<div class="back">
<div id="map-load">
<i class="fa fa-map-marker"></i>
</div>
<div id="maps-container">
<div id="googleMap"></div>
</div>
<i class="fa fa-times"></i>
</div>
<!-- END Back Card -->
</div>
</div>
</div>
<!-- No Matches -->
<div class="no-match" ng-show="filtered.length == 0">
<h3 class="no-matchText">Your search provides no matches!</h3>
</div>
<!-- END No Matches -->
</div>
<!-- END Employee -->
</div>
<!-- END Search Content -->
<!-- Next & Previous Buttons -->
<div class="btn-nextprev">
<div class="next-container">
<a href="" class="btn btn-next" id="next">
</a>
</div>
<div class="prev-container">
<a href="" class="btn btn-prev" id="prev">
</a>
</div>
</div>
<!-- END Next & Previous Buttons -->
</div>
<!-- END Slider Container -->
AngularJS:
Controller
var personControllers = angular.module('personControllers', ['ngAnimate']);
//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http',
function($scope, $http) {
$http.get('../static/scripts/data2.json').
success(function(data) {
console.log("JSON file loaded");
console.log(data);
$scope.employees = data;
//$scope.empOrder = 'name';
}).
error(function(){
console.log("JSON file NOT loaded");
});
}]);
EDIT
Updated Controller
var personControllers = angular.module('personControllers', ['ngAnimate']);
//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http',
function($scope, $http) {
$http.get('../static/scripts/data2.json').
success(function(data) {
console.log("JSON file loaded");
console.log(data);
$scope.employees = data;
//$scope.empOrder = 'name';
//Next & Previous Button Category Label
$scope.getNextCategoryIndex = function(currentIndex){
var nextIndex = currentIndex+1;
if( nextIndex >= $scope.employees.length ){
//move to start if at list end
nextIndex = 0;
}
return nextIndex;
}
$scope.getPrevCategoryIndex = function(currentIndex){
var prevIndex = currentIndex+1;
if( prevIndex < 0 ){
//move to the last index, if already at the start
prevIndex = $scope.employees.length - 1;
}
return prevIndex;
}
}).
error(function(){
console.log("JSON file NOT loaded");
});
}]);
Updated Next/Previous Buttons
<!-- Next & Previous Buttons -->
<div class="btn-nextprev">
<div class="next-container">
<a href="" class="btn btn-next" id="next">
{{ employees[getNextCategoryIndex($index)].category }}
</a>
</div>
<div class="prev-container">
<a href="" class="btn btn-prev" id="prev">
{{ employees[getPrevCategoryIndex($index)].category }}
</a>
</div>
</div>
<!-- END Next & Previous Buttons -->

I would probably do something like this: create functions to your controller to get the previous and next indexes (to handle the index overflows):
$scope.getNextCategoryIndex = function(currentIndex) {
var nextIndex = currentIndex+1;
if (nextIndex >= $scope.employees.length) {
// move over to start if we already were at the end of the list
nextIndex = 0;
}
return nextIndex;
}
$scope.getPrevCategoryIndex = function(currentIndex) {
var prevIndex = currentIndex+1;
if (prevIndex < 0) {
// move over to the last index, if we already are at the start
prevIndex = $scope.employees.length - 1;
}
return prevIndex;
}
And then in the HTML call those functions using $index (the current index of ng-repeat, see AngularJS documentation for ngRepeat for more details) as parameter:
<!-- Next & Previous Buttons -->
<div class="btn-nextprev">
<div class="next-container">
<a href="" class="btn btn-next" id="next">
{{employees[getNextCategoryIndex($index)].category}}
</a>
</div>
<div class="prev-container">
<a href="" class="btn btn-prev" id="prev">
{{employees[getPrevCategoryIndex($index)].category}}
</a>
</div>
</div>
<!-- END Next & Previous Buttons -->

The code you need should be:
{{employees[$index - 1].category}} //For the prev
{{employees[$index + 1].category}} //For the next

Recent Update (09-Apr-2015):
I have now been able to achieve what I wanted, on click of the button the relevant function runs and loops through the category names. One more thing to add now is that the buttons run in sync.
Controller
//Next & Previous Button Category Label
$scope.i = 0;
$scope.j = $scope.employees.length;
$scope.nextCat = $scope.i + 1;
$scope.prevCat = $scope.j - 1;
$scope.getNext = function(){
//console.log($scope.nextCat);
$scope.nextCat++;
if( $scope.nextCat >= $scope.employees.length ){
$scope.nextCat = 0;
}
$scope.prevCat++;
if( $scope.prevCat >= $scope.employees.length ){
$scope.prevCat = 0;
}
};
$scope.getPrev = function(){
//console.log($scope.nextCat);
$scope.prevCat--;
if( $scope.prevCat < 0 ){
$scope.prevCat = $scope.employees.length - 1;
}
$scope.nextCat--;
if( $scope.nextCat < 0 ){
$scope.nextCat = $scope.employees.length - 1;
}
};
HTML
<!-- Next & Previous Buttons -->
<div class="btn-nextprev">
<div class="next-container">
<a href="" class="btn btn-next" id="next"
ng-click="getNext()">
</a>
{{ employees[nextCat].category }}
</div>
<div class="prev-container">
<a href="" class="btn btn-prev" id="prev"
ng-click="getPrev()">
</a>
{{ employees[prevCat].category }}
<!-- {{ employees[prevCat].category }} -->
</div>
</div>
<!-- END Next & Previous Buttons -->
Update:
This is still not going to be a viable solution. I am technically able to achieve what is required however I am still required to use position: fixed. This means that the Category label then disappears.
I am now going to try and achieve this without it being within the ng-repeat and using ng-click it will iterate to the next Category name. Hopefully this will be the solution, and I will update upon any success/failure.
Update:
I am yet to find my optimal solution however, my current workaround for this utilises #jmustonen's solution.
Outside of the bxSlider I have the custom arrow's (if I placed these inside there were issues with the arrows not duplicating across pages - I believe there's an issue with it when it has position:fixed).
Then within my ng-repeat I include...
{{ employees[getNextCategoryIndex($index)].category }}
I will then be required to do some CSS in order for this to appear as if it is displayed as part of the Next/Previous buttons. Again these become invisible if position: fixed is used.

Related

Creating a remove and add button in JavaScript for a cart

I'm working on a project to create a shopping cart in a beginners JavaScript course. So far I've managed to add items to a cart and multiply their value to a subtotal. Where I'm failing is that my + and - aren't working, so I cannot add an idem twice? I get the
Uncaught TypeError: cannot set property 'innerHTML' of null
And I have read that To recap, this error occurs commonly when you try to modify an HTML element that has not appeared yet on the page. The solution is to move your JavaScript code from the head tag below the HTML element.
New to web-development... anyways below is my code.
const products = [{
"id": 1,
"name": "Aloe Vera",
"origin": "Nederländerna",
"description": "Lättskött suckulent med tjocka gröna blad. En av världens äldsta läkeväxter",
"height": "Höjd: 120cm",
"care": "Lättskött suckulent som trivs ljust, men undvik direkt solljus.",
"image": "img/alovera.jpeg",
"price": 100
},
{
"id": 2,
"name": "Citronfikus",
"origin": "Danmark",
"description": "En vacker växt med blanka, små gröna blad.",
"height": "Höjd: 50cm",
"care": "Passar bra i uterummet sommartid.",
"image": "img/citronfikus.jpeg",
"price": 150
},
{
"id": 3,
"name": "Hampa",
"origin": "Jamaica",
"description": "En fin växt med väldigt vackra blad med magiska egenskaper.",
"height": "Höjd: 50-100cm",
"care": "Passar bra i uterummet sommartid, vänt mot öst eller väst.",
"image": "img/hemp.jpg",
"price": 200
}
];
/* This section her renders all the items I've added to the cart, it also uses the id's that my objects have saved in the array that I created. I try to generate this button when rendering an item but it doesn't change the amount of items... I don't know why */
function renderCartItems() {
cartItemsEl.innerHTML = ""; // clear cart element
cart.forEach((item) => {
cartItemsEl.innerHTML += `
<div class="cart-item">
<div class="item-info" onclick="removeItemFromCart(${item.id})">
<img src="${item.image}" alt="${item.name}">
<h4>${item.name}</h4>
</div>
<div class="unit-price">
${item.price}:-
</div>
<div class="units">
<div class="btn minus" onclick="changeNumberOfUnits('minus', ${item.id})">-</div>
<div class="number">${item.numberOfUnits}</div>
<div class="btn plus" onclick="changeNumberOfUnits('plus', ${item.id})">+</div>
</div>
</div>
`;
});
}
/* this section creates a function that is supposed to update the numberOfUnits with the - and + buttons that are generated from the code above. But when I press them nothing happens, it doesn't change the number of units and is never updated...*/
function changeNumberOfUnits(action, id) {
cart = cart.map((item) => {
let numberOfUnits = item.numberOfUnits;
if (item.id === id) {
if (action === "minus" && numberOfUnits > 1) {
numberOfUnits--;
} else if (action === "plus" && numberOfUnits < 1) {
numberOfUnits++;
}
}
return {
...item,
numberOfUnits,
};
});
updateCart();
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.5.0/font/bootstrap-icons.css">
<div class="app-container">
<div class="app-bg">
<div class="left-side"></div>
<div class="right-side"></div>
</div>
<header>
</header>
<div class="products-list">
<div class="products">
<!-- render porducts here -->
</div>
<div class="cart">
<div class="cart-header">
<div class="column1">Vara</div>
<div class="column2">Pris</div>
<div class="column3">Antal</div>
</div>
<div class="cart-items">
<!-- render cart items here -->
</div>
<div class="cart-footer">
<div class="subtotal">
Totalt (0 varor): 0
</div>
<div class="checkout">
Vidare till betalning
</div>
</div>
</div>
</div>
Oh man so annoying! But I found the solution, in order to be able to increase the amount of items in the cart I have to check if the value is > or < then the actual number added so I solved it like this.
// change number of units for an item
function changeNumberOfUnits(action, id) {
cart = cart.map((item) => {
let numberOfUnits = item.numberOfUnits;
if (item.id === id) {
if (action === 'minus' && numberOfUnits >= numberOfUnits) {
numberOfUnits--;
} else if (action === 'plus' && numberOfUnits <= numberOfUnits) {
numberOfUnits++;
}
}
return {
...item,
numberOfUnits,
};
});
updateCart();

Get selected option from select with angular JS and ionic

I have some issues with select on angular Js, I searched a lot and found some solutions but not working.
I have a Json Structured like that generated from my service.php
[
{
"Name": "Name1",
"Variante": [
{
"Prix": "79.00",
"Name": "20 Piéces"
}
],
"Description": "",
"main_image": "images/products/DSC_0192.jpg"
},
{
"Name": "NAME2",
"Variante": [
{
"Prix": "39.00",
"Name": "250g"
},
{
"Prix": "60.00",
"Name": "500g"
}
],
"Description": "",
"main_image": "images/products/DSC_0125.jpg"
}
]
Here is my controller.js
.controller('productsCtrl', function($scope, $http, $stateParams) {
$http.get('service.php')
.success(function (response) {
$scope.products = response;
});
});
Here is my products.html
<ion-view view-title="Products">
<ion-content>
<ion-list>
<ion-item style="background-image: url({{product.main_image}})"
ng-repeat="product in products" class="productListItem">
<h2 class="h2Name">{{product.Name}}</h2>
<button class="button button-balanced button-right">
<i class="icon ion-ios-cart"></i>
</button>
<select class="Variantes"
ng-if="product.Variante.length > 1"
ng-model="selectedItem"
ng-options="variant.Name for variant in product.Variante">
</select>
<h2 class="Variantes" ng-if="product.Variante.length == 1">
{{product.Variante[0].Name}}
</h2>
<h2 class="h2Price" ng-if="product.Variante.length > 1">
{{selectedItem.Prix}}
</h2>
<h2 class="h2Price" ng-if="product.Variante.length == 1">
{{product.Variante[0].Prix}}
</h2>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
If I have more than one VarianteI want to be able to change the price (Prix) value when I change the select box. But it doesn't work.
Any help needed !!
Thanks
The issue you have is due to the ng-if. It creates a separate scope, use ng-show instead cause it uses the same scope and your code should work perfectly.
Using ng-show would work but you could also use ng-if if you're taking care of the dot rule for ng-model.
If you would add your selectedItem to the product object your markup with ng-if will work as expected. Your ng-model for the select would be like ng-model="product.selectedItem".
Please have a look at the demo below or in this jsfiddle.
var jsonData = [
{
"Name": "Name1",
"Variante": [
{
"Prix": "79.00",
"Name": "20 Piéces"
}
],
"Description": "",
"main_image": "images/products/DSC_0192.jpg"
},
{
"Name": "NAME2",
"Variante": [
{
"Prix": "39.00",
"Name": "250g"
},
{
"Prix": "60.00",
"Name": "500g"
}
],
"Description": "",
"main_image": "images/products/DSC_0125.jpg"
}
];
angular.module('demoApp', ['ionic'])
.controller('productsCtrl', function($scope, $http, $stateParams) {
$scope.product = {
selectedItem: {}
};
//$http.get('service.php')
//.success(function (response) {
//http just removed for the demo
$scope.products = jsonData;//response;
//});
});
<script src="http://code.ionicframework.com/1.1.0/js/ionic.bundle.js"></script>
<link href="http://code.ionicframework.com/1.1.0/css/ionic.css" rel="stylesheet"/>
<ion-view ng-app="demoApp" ng-controller="productsCtrl" view-title="Products">
<ion-content>
<ion-list>
<ion-item style="background-image: url({{product.main_image}})"
ng-repeat="product in products" class="productListItem" ng-init="product.selectedItem = product.Variante[0]">
<h2 class="h2Name">{{product.Name}}</h2>
<button class="button button-balanced button-right">
<i class="icon ion-ios-cart"></i>
</button>
<select class="Variantes"
ng-if="product.Variante.length > 1"
ng-model="product.selectedItem"
ng-options="variant.Name for variant in product.Variante">
</select>
<h2 class="Variantes" ng-if="product.Variante.length == 1">
{{product.Variante[0].Name}}
</h2>
<h2 class="h2Price" ng-if="product.Variante.length > 1">
{{product.selectedItem.Prix | currency}}
</h2>
<h2 class="h2Price" ng-if="product.Variante.length == 1">
{{product.Variante[0].Prix | currency}}
</h2>
</ion-item>
</ion-list>
</ion-content>
</ion-view>

ng-repeat disable my div

I for my stage have to modifie a web site for that i need angularjs i wanted to use the command ng-repeat to display some documentation but when i add ng-repeat in the div it "destroy" it and i cant figure out why...
So there is the code hope u can help me.
There is my js
App.controller('doccontroller', [ function(){
return {
scope: {},
restrict: 'A',
link: function ($scope){
$scope.docs = [
{
"id_section" : 0,
"description": "RANDOM STUFF",
"source": [
{
"python": "TEXTE",
"ruby": "TEXTE",
"javascript": "TEXTE"
}
]
},
{
"id_section" : 1,
"description": "RANDOM STUFF",
"source": [
{
"python": "TEXTE",
"ruby": "TEXTE",
"javascript": "TEXTE"
}
]
},
{
"id_section" : 2,
"description": "RANDOM STUFF",
"source": [
{
"python": "TEXTE",
"ruby": "TEXTE",
"javascript": "TEXTE"
}
]
}
]
}
}
}
])
`There is my route to "include" the controller
$routeProvider.when '/docs',
templateUrl : config.BaseHtml+'/Page/docs.html'
controller : 'doccontroller'
`
and to finish the html :)
<div id="api-docs">
<div id="methods">
<div class="languages">
<a class="language selected" data-lang="ruby" href="#">Ruby</a>
<a class="language" data-lang="python" href="#">Python</a>
<a class="language" data-lang="php" href="#">PHP</a>
</div>
<div>
<div class="method" id="intro">
<div class="method-section clearfix">
<div class="method-description" ng-repeat="doc in docs">
<h3>Introduction</h3>
<p>
{{doc.description}}
</p>
</div>
<div class="method-example">
<pre>
<code class="ruby"># All this code is just folololol
React.api_key = "In here goes your api key!"</code><code class="python"># All this code is just for demonstration purposes
react.api_key = "In here goes your api key!"</code><code class="php"># All this code is just for demonstration purposes
React::setApiKey("In here goes your api key!");</code>
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
So to say it again, what i need to do is to fill create 1 div / id_section and to fill it with the
descrition for now.
Change:
ng-repeat="docs in docs"
to:
ng-repeat="doc in docs"
Also, in your code you have a call to {{ doc.des }}, which probably should be {{ doc.description }}

angular js to keep track of like and dislike click

I am trying to develope app in angularjs where i am reading json to read comments with like and dislike button . i am stuck at point where i am not sure how to track if user has already clicked on Like for particular comment ??
data.json::
[ {
"name": "Anam",
"age": 20,
"id": 100,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Moroni",
"age": 50,
"id": 101,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Tiancum",
"age": 43,
"id": 102,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Jacob",
"age": 27,
"id": 103,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Nephi",
"age": 29,
"id": 104,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Anam",
"age": 20,
"id": 100,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
}
]
HTML ::
<!DOCTYPE html>
<html ng-app="FundooDirectiveTutorial">
<head>
<title>Rating Directive Demo</title>
<link rel="stylesheet" href="rating.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<style>
.sideheading
{
display: inline-block
}
</style>
</head>
<body ng-controller="FundooCtrl">
<h2>Listing All Comments </h2>
<br/><!--
<div class="commentbox" ng-repeat="comment in comments" >
<h4 class="sideheading">comment By:</h4>{{comment.name}}<br/>
<h4 class="sideheading">Comment ::</h4>{{comment.commentline}} <br/>
<h4 class="sideheading">Likes ::</h4> {{comment.like}} <br/>
<h4 class="sideheading">Dislike::</h4> {{comment.dislike}} <br/>
</div>
-->
<div class="panel panel-default" ng-repeat="comment in comments">
<div class="panel-heading">
<h3 class="panel-title">{{comment.name}}</h3>
</div>
<div class="panel-body">
Comment ::{{comment.commentline}} <br/>
Likes :: {{comment.like}}
<button type="button" class="btn btn-default btn-xs" ng-click="incrlikes(comment)">
<span class="glyphicon glyphicon-star"></span> Like
</button>
<button type="button" class="btn btn-default btn-xs" ng-click="decrlikes(comment)">
<span class="glyphicon glyphicon-star"></span> DisLike
</button><br/>
Dislike:: {{comment.dislike}}
<br/>
likeflag::
<br/>
</div>
</div>
<!-- <div fundoo-rating rating-value="rating" max="10" on-rating-selected="saveRatingToServer(rating)"></div>
<br/>
Readonly rating <br/>
<div fundoo-rating rating-value="rating" max="10" readonly="true"></div>
-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script type="text/javascript" src="comment.js"></script>
</body>
</html>
JS ::
var app=angular.module('FundooDirectiveTutorial', []);
app.controller('FundooCtrl', function ($scope, $http) {
$http.get('comment.json').success(function(data) {
$scope.comments = data;
$scope.incrlikes=function(a)
{
var selectedIndex=$scope.comments.indexOf( a );
console.log('Likes increment'+a.name);
console.log($scope.comments.indexOf( a ) +'with index of name is '+$scope.comments[selectedIndex].name );
$scope.comments[selectedIndex].like=$scope.comments[selectedIndex].like+1;
$scope.likeflag=1;
if($scope.likeflag==1)
{
}else
{
console.log('Already like');
}
}
});
});
Fiddle::
http://jsfiddle.net/simmi_simmi987/DeKP4/
I solved my this problem using ng-show and ng-hide,
when likeClicked is false then i show like button , and when user click it on it i change variable to false . so automaticaly , dislike button is shown
var app=angular.module('FundooDirectiveTutorial', []);
app.controller('FundooCtrl', function ($scope, $http) {
$http.get('comment.json').success(function(data) {
$scope.comments = data;
$scope.likeClicked=[];
$scope.incrlikes=function(a)
{
var selectedIndex=$scope.comments.indexOf( a );
if(! $scope.likeClicked[selectedIndex])
{
console.log('Likes increment'+a.name);
console.log($scope.comments.indexOf( a ) +'with index of name is '+$scope.comments[selectedIndex].name );
$scope.comments[selectedIndex].like=$scope.comments[selectedIndex].like+1;
$scope.likeClicked[selectedIndex]=true;
}
else
{
console.log('Already like');
}
}
$scope.decrlikes=function(a)
{
var selectedIndex=$scope.comments.indexOf( a );
if($scope.likeClicked[selectedIndex])
{
console.log('Likes increment'+a.name);
console.log($scope.comments.indexOf( a ) +'with index of name is '+$scope.comments[selectedIndex].name );
$scope.comments[selectedIndex].like=$scope.comments[selectedIndex].like-1;
$scope.likeClicked[selectedIndex]=false;
}
else
{
console.log('Already Dislike');
}
}
});
});

Passing data into foundation modals using angularjs repeater

I'm making a "members" page for a website, which has 3 columns of pictures and names for each member. I want to be able to click on the picture to get more information about that member (via Foundation's modal). I'm using a repeater to display the pictures, but I'm stuck on how to pass member data into the modal so that when I click on person A, the modal will have person A's data.
Here is what I have so far:
I store the members as a json list in members.json:
{
"current" : [
{
"name": "Bob",
"pic": "http://www.placehold.it/300x300",
"id": "blah",
"position": "position 1",
"bio": "Hi I am Bob"
},
{
"name": "Bobby",
"pic": "http://www.placehold.it/300x300",
"id": "blah",
"position": "position 2",
"bio": "Hi I am Bobby"
}
]
}
And here is my controller, uses the json file:
var app = angular.module('app').controller('memberCtrl', ['$scope', '$http', function ($scope, $http) {
'use strict';
$http.get('/data/members.json').success(function(data) {
$scope.members = data;
$scope.numColumns = 3;
$scope.current_rows = [];
$scope.current_rows.length = Math.ceil($scope.members.current.length / $scope.numColumns);
$scope.current_cols = [];
$scope.current_cols.length = $scope.numColumns;
});
}]);
And here is my html:
<!-- My attempt at the modal -->
<div ng-controller="memberCtrl" id="myModal" class="reveal-modal">
<div class="row">
<div class="large-3 columns">
<img src="http://www.placehold.it/300x300">
</div>
<div class="large-6 columns">
<center>
<!-- The following remains blank -->
<h2>{{members.current[$parent.$index * numColumns + $index].name}}</h2>
</center>
<p class="lead">Bio.</p>
<p>Hi</p>
</div>
<div class="large-3 columns">
<img src="http://www.placehold.it/300x300">
</div>
</div>
<a class="close-reveal-modal">×</a>
</div>
<!-- This creates a 3 column array of member profiles (it works) -->
<div ng-controller="memberCtrl">
<div class="row" data-ng-repeat="row in current_rows">
<div class="large-4 columns" data-ng-repeat="col in current_cols">
<img ng-src="{{members.current[$parent.$index * numColumns + $index].pic}}">
<center>
<small><h3>{{members.current[$parent.$index * numColumns + $index].name}}</h3></small>
<small><h4>{{members.current[$parent.$index * numColumns + $index].position}}</h4></small>
</center>
</div>
</div>
</div>
Add ng-click attr in the img:
<img ng-src="{{members.current[$parent.$index * numColumns + $index].pic}}"
ng-click="loadMember(members.current[$parent.$index * numColumns + $index]);"/>
And add the function in the controller:
$scope.loadMember = function (member) {
//you should be able to access the current member
console.log(member);
}
Demo on jsFiddle

Categories

Resources