AngularJS - how to iterate array on click - javascript

I have an array and I want to be able to go to the next index of the array whenever I click a button.
Html code where I call the function:
<div class="flex">
<div class="date-switcher">
<header>
<h1>{{ ctrl.percent}}</h1>
</header>
</div>
<div class="arrows-switch">
<div class="right-arrow" ng-click="nextValue()">
<a href="#"><img src="assets/images/images/images/arrow-sprite_02.png">.
</a>
</div>
</div>
</div>
And the jvs code where I try to iterate :
var ctrl = this;
var percent = [
{ value: 70,},
{ value: 93,},
{ value: 100,},
{ value: 94,},
{ value: 66,}
];
for(var i=0; i < percent.length;i++) {
ctrl.percent = percent[i].value
break
}
$scope.nextValue = function() {
ctrl.percent = percent[i+1].value
}
The output from header h1 {{ctrl.percent}} is 70 which is the ctrl.percent first array item, but when I call the function nextValue, it goes to the second array item and stops.
How can I make it keep going to the next array item till the last?
Expected:
1st click - 2nd array item
2nd click 3rd array item
etc...

indexValue = 0;
$scope.nextValue = function() {
this.percent = percent[indexValue+1].value
}
Declare the index value as a global variable. I think this should do the trick.

Related

I would like to delete an item off my todo list and my object array at the same time with jQuery [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 3 years ago.
I have my code set up to be able to delete an item on the HTML side of things but after I add a new item the old item appears due to it not being deleted from my array I made. I would like to delete the array item associated with the list item I deleted.
HTML
<div class="list-content">
<ul id="display_list">
<li class="item">
<img src="./img/icons/checked.svg">
<p class="text">Take car to get oil change</p>
<img id="trash" src="./img/icons/trash.svg"
onclick="trashClicked(this)">
</li>
</ul>
</div>
Javascript
let listItems = [];
function addItem() {
let input = $('#item_input').val();
let tempobj = {};
tempobj.listname = input;
listItems.push(tempobj);
$('#item_input').val('');
printmypage();
};
function printmypage() {
$('#display_list').html('');
for(var i = 0; i < listItems.length; i ++) {
$('#display_list').append(`
<li class="item">
<img src=${unchecked}>
<p class="text">${listItems[i].listname}</p>
<img id="trash" src="./img/icons/trash.svg"
onclick="trashClicked(this)">
</li>
`);
};
};
function trashClicked(el) {
console.log(listItems[1]);
console.log(el);
$(el).parent().remove();
};
I would like it when I click my trash svg icon in the function trashClicked() to delete that item in my listItems array. So when I go to add the next item it doesn't have it in my array.
You can get the index of el using jQuery's .index() function (on the li element, which is its parent, or grandparent in my example). Then, with the value of the index, you call splice() on the array.
Here you can see it in action (I call $(el).parent().parent() because I wrapped the remove button inside a div):
let listItems = [{listname: 'Take car to get oil change'}];
printmypage();
function addItem() {
let input = $('#item_input').val();
let tempobj = {};
tempobj.listname = input;
listItems.push(tempobj);
$('#item_input').val('');
printmypage();
};
function printmypage() {
$('#display_list').html('');
for(var i = 0; i < listItems.length; i ++) {
$('#display_list').append(`
<li class="item">
<div class="text">${listItems[i].listname}
<button onclick="trashClicked(this)">x</button>
</div>
</li>
`);
};
};
function trashClicked(el) {
listItems.splice($(el).parent().parent().index(), 1);
$(el).parent().parent().remove();
printmypage();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="item_input"/>
<button type="button" onclick="addItem()">Add</button>
<div class="list-content">
<ul id="display_list">
</ul>
</div>

Add entries from the top in to-do list angular

I have made this to-do list in angular but would like the posts entered to entered fro m the top instead the bottom.
my code:
HTML
<a href="{{url.title}}" class="link">
<p class="title">{{url.name}}</p>
<p class="url">{{url.title}}</p>
</a>
</div>
<div class="col-md-4 delete m-b-2">
<!--a href="javascript:" ng-click="edit($index)" type="button" class="btn btn-primary btn-sm">Edit</a-->
Delete
</div>
</div>
</li>
JS
var urlFire = angular.module("UrlFire", ["firebase"]);
function MainController($scope, $firebase) {
$scope.favUrls = $firebase(new Firebase('https://lllapp.firebaseio.com/'));
$scope.urls = [];
$scope.favUrls.$on('value', function() {
$scope.urls = [];
var mvs = $scope.favUrls.$getIndex();
for (var i = 0; i < mvs.length; i++) {
$scope.urls.push({
name: $scope.favUrls[mvs[i]].name,
title: $scope.favUrls[mvs[i]].title,
key: mvs[i]
});
};
});
You can use unshift() instead of push() when you add elements to your array. It adds the element at the beginning of your array instead of at the end, and since your angular view is based on the model it will add it on top.
Use $scope.urls.splice(index_to_insert,0, object); so in your case you could do
var obj = {
name: $scope.favUrls[mvs[i]].name,
title: $scope.favUrls[mvs[i]].title,
key: mvs[i]
};
$scope.urls.splice(0,0, obj);

Really odd for loop behavior

I'm comparing 2 integers in a loop which loops through an array which contains JSON objects. The JSON objects contain an ID and a Name. When I click on the close button of my window that window should disappear and the others should remain but what happens is that if I close the window with the highest ID all of them get close and if for example I close the fifth one the #1-5 gets closed but the higher IDs remain.
ctrl.items = [{
id: 1,
name: "Number one"
},
{
id: 2,
name: "Number two"
},
{
id: 3,
name: "Number three"
}];
ctrl.removeWindow = function(toBeRemovedId) {
console.log("Called: " + toBeRemovedId);
for (var i = ctrl.items.length - 1; i >= 0; i--) {
console.log(ctrl.items[i].id + " " + toBeRemovedId);
if(ctrl.items[i].id == toBeRemovedId) {
ctrl.items.splice(ctrl.items[i], 1);
}
};
}
<div class="window show" id="item_window" ng-repeat="item in itemWindowCtrl.items">
<hgroup>
<h1>{{ item.name}}</h1>
<button class="close" ><span class="fa fa-times fa-lg" ng-click="itemWindowCtrl.removeWindow(item.id)"></span></button>
</hgroup>
<section>
<p>{{ item.id + " " + item.name }}</p>
</section>
</div>
Thanks in advance for any clues you might be able to bring me.
The array splice function takes the index, rather than the item to remove, so you should just be doing:
ctrl.items.splice(i, 1);
The looping is a bit unnecessary though. Why don't you just pass through the item to be removed rather than looping through in descending id order to find matching, id? For example:
ng-click="itemWindowCtrl.removeWindow(item)"
Then in your controller / directive:
ctrl.items.splice(ctrl.items.indexOf(item), 1);
change the for loop to get the index and then just remove that index
var index = -1;
for (var i = 0; i < ctrl.items.length; i++) {
if(ctrl.items[i].id === toBeRemovedId) {
index = i;
}
};
ctrl.items.splice(index, 1);

Finding item of array base on the ng-repeater index in Angular

In my application i have 2 array of object.layout array is for creating twitter bootstrap layout.this array is like below :
$scope.layout = [
{c:[{size:12}]},
{c:[{size:2},{size:3},{size:4},{size:3}]},
{c:[{size:3},{size:5},{size:4}]}
];
you can see how this array work in this jsbin.the other array is items array and this array is like below:
$scope.items =[
{row:1,column:0,names:['Jack','Daniel']},
{row:3,column:3,names:['Eli','Bill']},
{row:2,column:1,names:['Fred','David']}
];
and this is the repeater that i used :
<div ng-repeat="(ri,r) in layout" class="row">
<div ng-repeat="(ci,c) in r.c" class="col-md-{{c.size}} col-sm-{{c.size}} col-xs-{{c.size}} col-lg-{{c.size}} bi"> Row{{ri}}-Column{{ci}}
//Maybe other repeater come here
</div>
</div>
now i want when i want to display Jack , Daniel in row 1 column 0 and this 1 and 0 is r and c in repeater of first and second repeater.so when the repeater create row 2 column 1 also repeat on $scop.item and find the related names. but i don't know how to find items in $scope.item.and this is my jsbin
You can do something like this:
<div ng-repeat="(ri,r) in layout" class="row">
<div ng-repeat="(ci,c) in r.c" class="col-md-{{c.size}} col-sm-{{c.size}} col-xs-{{c.size}} col-lg-{{c.size}} bi">
{{getNames(ri, ci)}}
</div>
</div>
Where getNames is defined in controller:
$scope.getNames = function(r, c) {
var items = $scope.items;
for (var i = 0; i < items.length; i++) {
if (items[i].row == r && items[i].column == c) {
return items[i].names;
}
}
return '';
};
Demo: http://jsbin.com/sumuwigo/1/edit

Adding get() to line causes "is not a function" error

This is the start of an inventory system I am working on. Basically it takes an array with items and quantities in a compressed form and outputs the items into an item div.
Running the below produces no error:
$('.item_amount').html(collection[itemName].amo);
Adding the get() method after the selector like so:
$('.item_amount').get(i).html(collection[itemName].amo);
produces "$(".item_amount").get(i).html is not a function".
This is what the line is altering:
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
The line that is causing the error is located in a for loop that loops through all the keys in an array. Then outputs the item quantity from the array in the item_amount div based on the index stored in the variable "i". The for loop also creates an object for each item in the array and puts in the a collection object.
Full code below:
<body>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<script type="text/javascript">
var collection = new Object();
function makeItem(itemName, id, amo) {
collection[itemName] = new item(id, amo);
}
function item(id, amo) {
this.id = id;
this.amo = amo;
}
var inventoryCom = "368.9,366.15,384.32"; //compressed inventory
var inventoryArr = inventoryCom.split(',');
for(var i=0; i < inventoryArr.length; i++) {
var itemName = 'item' + (i + 1); //unique name for each item
var itemArr = inventoryArr[i].split('.');
makeItem(itemName, itemArr[0], itemArr[1]);
$('.item_amount').get(i).html(collection[itemName].amo);
}
</script>
</body>
.get(i) returns DOM element, which doesn't have .html() method - that's what js engine wants to say to you.
You need to use .eq(i) instead. Like
$('.item_amount').eq(i).html(collection[itemName].amo);
or
$('.item_amount:eq(' + i + ')').html(collection[itemName].amo);
This line may be a problem
var itemName = 'item' + (i + 1); //
This may increment the array count out of the upper bound. check the itemName value.
Also try to add an alert for this
collection[itemName].amo

Categories