AngularJS: Add toggle function to an image inside ng-repeat - javascript

I am using ng-repeat for div element. I have a toggle function on image inside div element. However, when I click on image, function gets triggered but it is showing up same data for all divs. Below is the code.
HTML :
<div ng-repeat="item in items">
<div>
<img src="img/icon1.png" class="pull-right" ng-click="showDiv(item.itemId,$index)">
</div>
<div ng-show="hiddenDiv[$index]">
<div ng-repeat="student in studentData">
<div class="row">
<div>
<div>{{student.name}}</div>
<div>{{student.adress}}</div>
</div>
</div>
</div>
</div>
</div>
JS :
$scope.hiddenDiv=[];
$scope.showDiv=function(itemId,index) {
$scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
var myResult = ListService.getList(url here);
myResult.then(function (data) {
if(data && data.list)
$scope.studentData = data.list;
});
}
Here, I am using same scope variable in all divs inside ng-repeat.
Updated Answer :
js :
$scope.studentData = [];
$scope.studentData[index] = data.list;
HTML :

If you want to have unique students for every item, you need to do something like this:
<div ng-repeat="item in items">
<div>
<img src="img/icon1.png" class="pull-right" ng-click="showDiv(item.itemId,$index)">
</div>
<div ng-show="hiddenDiv[$index]">
<div ng-repeat="student in item.studentData">
<div class="row">
<div>
<div>{{student.name}}</div>
<div>{{student.adress}}</div>
</div>
</div>
</div>
</div>
</div>
and js:
$scope.hiddenDiv=[];
$scope.showDiv=function(itemId,index) {
$scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
var myResult = ListService.getList(url here);
myResult.then(function (data) {
if(data && data.list)
$scope.items[index].studentData = data.list;
});
}
or use the same as for hiddenDiv
$scope.hiddenDiv=[];
$scope.studentData = [];
$scope.showDiv=function(itemId,index) {
$scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
var myResult = ListService.getList(url here);
myResult.then(function (data) {
if(data && data.list)
$scope.studentData[index].studentData = data.list;
});
}
and html:
<div ng-repeat="student in studentData[$index]">

Related

Angular/Ionic ng-repeat + ng-init $scope variable parameter passing

Im trying to call a function inside ng-init using the result of ng-repeat but the only image displayed is the last image that was pass to the scope variable.
Any tips or suggestion if im doing this correctly?
Template
<ion-item ng-repeat="feed in feeds" ng-if=fbfeed.message ng-init='addAttachment(feed.id)'>
<div class="list card">
<div class="item item-body">
<img src="{{attachment.media.image.src}}">
</div>
</div>
</ion-item>
Controller
$scope.addAttachment = function (postId) {
var attachmentData = MediaManager.getAttachments( postId );
attachmentData.then(function(result) {
if (result.data.length) {
$scope.attachment = result.data[0];
}
});
};
You need to add the attachment field with all the objects . so add that to the object feed .
You can pass the feed id and assign the corresponding image in the function.
HTML
<ion-item ng-repeat="feed in feeds" ng-if=fbfeed.message ng-init='addAttachment(feed)'>
<div class="list card">
<div class="item item-body">
<img src="{{feed.attachment.media.image.src}}">
</div>
</div>
</ion-item>
Controller:
$scope.addAttachment = function (feed) {
var attachmentData = MediaManager.getAttachments( feed.postId );
attachmentData.then(function(result) {
if (result.data.length) {
feed.attachment = result.data[0];
}
});
};

AngularJs, How to edit $scope values in other div using the same controller with factory

I would like to use two different divs one contains a form and other contains repeat for the $scope values. Those two divs needs to use the same controller. However I am not able to share data in between divs in a desired way. Although I use factory, it only helps for me to add data to scope. I also want to edit the scope values inside the form which has another instance of the same controller.
You can find what I did in this link.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>
<script>
var app = angular.module("myShoppingList", []);
app.factory('fact',function(){
products = ["milk","chese"];
tempItem = '';
tempIndex = undefined;
return {
getProducts : function() {
return products;
},
getProductByIndex : function(x){
return products[x];
},
saveProduct : function(x,item)
{
if(x==undefined)
{
products.push(item);
}
else
{
products[x] = item;
}
tempItem = '';
tempIndex = undefined;
},
editProduct : function(x)
{
tempItem = products[x];
tempIndex = x;
},
removeProduct : function(x)
{
products.splice(x, 1);
},
getTempItem : function()
{
return tempItem;
},
getTempIndex : function()
{
return tempIndex;
},
}
});
app.controller("myCtrl", function($scope, fact) {
$scope.products = fact.getProducts();
$scope.tempIndex = fact.getTempIndex();
$scope.tempItem = fact.getTempItem();
$scope.saveItem = function () {
fact.saveProduct($scope.tempIndex,$scope.tempItem);
}
$scope.editItem = function (x) {
fact.editProduct(x);
}
$scope.removeItem = function (x) {
fact.removeProduct(x);
}
});
</script>
<div ng-app="myShoppingList" ng-cloak class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<div ng-controller="myCtrl">
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{$index}} {{x}}
<span ng-click="editItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">||</span>
<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span>
</ul>
</div>
<div ng-controller="myCtrl" class="w3-container w3-light-grey w3-padding-16">
<form ng-submit="saveItem()">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="tempItem" class="w3-input w3-border w3-padding">
<input type="hidden" ng-model="tempIndex">
</div>
<div class="w3-col s2">
<button type="submit" class="w3-btn w3-padding w3-green">Save</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
ISSUES
You have initialized controller twice.
You can do edit item inside controller itself.
After saving $scope values should be cleared along with clearing values in factory.
CONTROLLER and HTML
var app = angular.module("myShoppingList", []);
app.factory('fact',function(){
products = ["milk","chese"];
tempItem = '';
tempIndex = undefined;
return {
getProducts : function() {
return products;
},
getProductByIndex : function(x){
return products[x];
},
saveProduct : function(x,item)
{
if(!x)
{
products.push(item);
}
else
{
products[x] = item;
}
tempItem = '';
tempIndex = '';
},
editProduct : function(x)
{
tempItem = products[x];
tempIndex = x;
},
removeProduct : function(x)
{
products.splice(x, 1);
},
getTempItem : function()
{
return tempItem;
},
getTempIndex : function()
{
return tempIndex;
},
}
});
app.controller("myCtrl", function($scope, fact) {
$scope.products = fact.getProducts();
$scope.tempIndex = fact.getTempIndex();
$scope.tempItem = fact.getTempItem();
$scope.saveItem = function () {
fact.saveProduct($scope.tempIndex,$scope.tempItem);
$scope.tempItem = '';
$scope.tempIndex = '';
}
$scope.editItem = function (x) {
$scope.tempItem = fact.getProducts()[x];
$scope.tempIndex = x;
}
$scope.removeItem = function (x) {
fact.getProducts().splice(x, 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<div ng-app="myShoppingList" ng-controller="myCtrl" ng-cloak class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<div>
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{$index}} {{x}}
<span ng-click="editItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">||</span>
<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span>
</ul>
</div>
<div class="w3-container w3-light-grey w3-padding-16">
<form ng-submit="saveItem()">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="tempItem" class="w3-input w3-border w3-padding">
<input type="hidden" ng-model="tempIndex">
</div>
<div class="w3-col s2">
<button type="submit" class="w3-btn w3-padding w3-green">Save</button>
</div>
</div>
</form>
</div>
</div>

Adding objects to the DOM after adding new data to the list

I have an array of objects which i populate on a button click.
When populating this array i make sure that i only add 10 objects to it.
When this is all loaded in the dom i give the user the oppertunity to add a few more objects.
I do this like this:
$scope.Information = [];
$.each(data, function (i, v) {
if (i<= 9)
$scope.Information.push(data[i]);
if(i >= 10) {
cookieList.push(data[i]);
}
}
if (cookieList.length) {
localStorage.setItem("toDoList", JSON.stringify(cookieList));
$(".showMore").removeClass("hidden");
}
$(".showMore").on("click", function() {
var obj = JSON.parse(localStorage.getItem("toDoList"));
console.log(obj);
console.log(obj.length);
SetSpinner('show');
$scope.Information.push(obj);
SetSpinner('hide');
//$.removeCookie("toDoList2");
});
part of the HTML:
<div ng-repeat="info in Information" class="apartment container" style="padding-right:35px !important">
<div class="row" style="height:100%">
<div class="col-md-1 col-xs-12">
<div>
<h4 class="toDoListHeadings">Nummer</h4>
<div style="margin-top: -15px; width:100%">
<span class="toDoListItems number">
{{info.orderraderid}}
</span>
</div>
</div>
</div>
</div>
</div>
My issue: When i add objects to my array of objects "$scope.Information.push(obj);" I assumed that they would get added in the DOM but they do not, how do i do this the angular way?
EDIT MY SOLOUTION:
edited the HTML to use ng-click and the method is as follows:
$scope.addMore = function() {
var obj = JSON.parse(localStorage.getItem("toDoList"));
SetSpinner('show');
$.each(obj, function(i,v) {
$scope.Information.push(v);
});
SetSpinner('hide');
}
Here is the angular way:
 The view
<!-- Reference your `myapp` module -->
<body data-ng-app="myapp">
<!-- Reference `InfoController` to control this DOM element and its children -->
<section data-ng-controller="InfoController">
<!-- Use `ng-click` directive to call the `$scope.showMore` method binded from the controller -->
<!-- Use `ng-show` directive to show the button if `$scope.showMoreButton` is true, else hide it -->
<button data-ng-click="showMore()" data-ng-show="showMoreButton">
Show more
</button>
<div ng-repeat="info in Information" class="apartment container" style="padding-right:35px !important">
<div class="row" style="height:100%">
<div class="col-md-1 col-xs-12">
<div>
<h4 class="toDoListHeadings">Nummer</h4>
<div style="margin-top: -15px; width:100%">
<span class="toDoListItems number">
{{info.orderraderid}}
</span>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
The module and controller
// defining angular application main module
var app = angular.module('myapp',[])
// defining a controller in this module
// injecting $scope service to the controller for data binding with the html view
// (in the DOM element surrounded by ng-controller directive)
app.controller('InfoController',function($scope){
$scope.Information = [];
$scope.showMoreButton = false;
// Bind controller method to the $scope instead of $(".showMore").on("click", function() {});
$scope.showMore = function(){
var obj = JSON.parse(localStorage.getItem("toDoList"));
console.log(obj);
console.log(obj.length);
SetSpinner('show');
$scope.Information.push(obj);
SetSpinner('hide');
//$.removeCookie("toDoList2");
};
$.each(data, function (i, v) {
if (i<= 9) $scope.Information.push(data[i]);
if(i >= 10) cookieList.push(data[i]);
});
if (cookieList.length) {
localStorage.setItem("toDoList", JSON.stringify(cookieList));
//$(".showMore").removeClass("hidden");
$scope.showMoreButton = true; // use $scope vars and ng-class directive instead of $(".xyz").blahBlah()
}
});
You should not use JQuery, use ng-click to detect the click, because angular has no idea when JQuery is done and when it needs to refresh the interface

Submitting multiple dynamic forms

I'm trying to submit multiple forms at once when a single button is clicked. These forms are all generated automatically. They all have different action urls but the same id's. That's how the system (SaaS) works.
The problem is that I'm having issues getting the correct selectbox values and then send the forms. I'm not getting any error but I think it has something to do with identifiers. I'm working on this one for a few days now and I can't figure this one out.
So for every set/product there's some empty html, like so:
HTML
<div id="sets" class="clearfix">
// first set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// second set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// etc... can be as much as 10 sets
</div><!-- .#sets -->
Inside the above HTML .product there comes an automatically generated form. This form is generated like so:
Jquery
$('#sets .set').each( function(){
$(this).click(function(){
if($(this).hasClass('open')){
$('.close').click(function(){
$('#sets .product').fadeOut();
$('.products',this).animate({
width: 'toggle'},500, function() {
.......
});
});
} else {
.....
}
var url = $(this).data('handle')+'?format=json';
$.getJSON(url, function (data){
var product = data.product;
var $container = $('.products .product');
var productsHtml = [];
var fullurl = 'http://www.shop.com';
var variants = '';
$.each(product.related, function(index, rel){
var url = ''+fullurl+''+rel.url+'?format=json';
...... etc ...
var productHtml = '<div id="'+rel.id+'" class="p"><form method="post" id="product_configure_form" action="http://www.shop.com/cart/add/'+rel.vid+'/" name="formsub"><div class="foto"><img class="rollover" src="'+image+'" hover="'+image2+'" alt="'+rel.fulltitle+'"/></div><div class="prijs" data-price="'+rel.price.price_incl+'">€'+rel.price.price_incl+'</div><div class="varianten_'+rel.id+'">';
$.getJSON(url, function (data){
var rel = data.product;
var wqsSelectVariants = $('<div class="product-configure-variants tui" />');
var select = $('<select id="product_configure_variants"/>');
$.each(rel.variants, function (index, variant){
select.append('<option value=' + variant.id + '>' + variant.title + '</option>');
wqsSelectVariants.append(select);
});
$('.varianten_'+rel.id).html(wqsSelectVariants);
});
var price = rel.price.price_incl;
sum += price;
productHtml = productHtml + '</div></form></div>';
productsHtml.push(productHtml);
});
$('.total').text('€'+sum.toFixed(2));
productsHtml = productsHtml.join('')
$container.html(productsHtml);
});
}
});
});
etc....
<script type="text/javascript">
$(document).ready(function(){
$(".trigger").on("click", function(e){
e.preventDefault();
$('form[name="formsub"]').each(function(){
var variant = $('#product_configure_variants').val();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action')+variant+'/?quantity=1',
data: $form.serialize(),
success: function(data, status){
if(status == 'success'){
}else if(status == 'error'){
}
}
});
});
});
});
</script>
Does anyone know what's going wrong or give me some directions on how to fix that?
Try using $('form[name="formsub"]:visible') as your selector. That should give you just the visible forms instead of all the ones on the page.

AngularJS not updating?

I'm not sure why this is not changing when its bound object changes:
My HTML:
<div id="account-info" ng-controller="AuthenticateCtrl">
<h5>Account: </h5>
{{account}}
</div>
<div ng-controller="AuthenticateCtrl">
<div modal="shouldBeOpen" options="opts">
<div class="modal-header">
<h3>Select your account</h3>
</div>
<div class="modal-body">
<div class="account-btn" ng-repeat="item in items" ng-click="close(item)">
{{item}}
</div>
</div>
</div>
</div>
My JavaScript:
var AuthenticateCtrl = function ($scope) {
$scope.account= "";
$scope.open = function() {
$scope.shouldBeOpen = true;
};
$scope.close = function(item) {
if (item) {
$scope.shouldBeOpen = false;
$scope.account= item;
}
};
}
For some reason it always displays nothing, or if I set $scope.account = "ANY STRING" it will display "ANY STRING" but won't update when the close function is called.
Ok an attempt with fiddle. Firstly you had two ng-controller directives pointing to the same function. Secondly I don't really understand the domain here, but I'm guessing this is what you need. Heres a fiddle.
<div ng-controller="AuthenticateCtrl">
<div id="account-info">
<h5>Account: </h5>
{{account.name}}
</div>
<div>
<div modal="shouldBeOpen" options="opts">
<div class="modal-header">
<h3>Select your account</h3>
</div>
<div class="modal-body">
<div class="account-btn" ng-repeat="item in items" ng-click="close(item)">
{{item.name}}
</div>
</div>
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp',[]);
var AuthenticateCtrl = function ($scope) {
$scope.opts = {};
$scope.account = {};
$scope.items = [
{'name':'one'},
{'name':'two'}
];
$scope.open = function() {
$scope.shouldBeOpen = true;
};
$scope.close = function(item) {
if (item) {
$scope.shouldBeOpen = false;
$scope.account= item;
}
};
}
</script>

Categories

Resources