I try to delete element from array of objects:
ng-click="deleteSpecialization(item)"
Where item is item from ng-repeat:
ng-repeat="item in data"
My function:
$scope.deleteSpecialization = function (item) {
var index = $scope.data.indexOf(item);
if (index != -1) {
$scope.data.splice(index, 1);
}
}
This code removes some items in template HTML after second click. I do one ng-clickbut template changes incorrect.
Format:
[{"name":"A","checked":false,"id":"6"},{"name":"B","checked":false,"id":"8"},{"name":"C","checked":false,"id":"10"},{"name":"D","checked":false,"id":"12"},
Here is the working demo of splice functionality, although you write the absolutely fine for splice.
https://codepen.io/kashifmustafa/pen/VvjqwE
$scope.deleteSpecialization = function (item) {
var index = $scope.data.indexOf(item);
if (index != -1) {
$scope.data.splice(index, 1);
}
}
Hello Demo is here http://jsfiddle.net/qjcqwhsw/2/
$scope.deleteItem = function(item){
var index = $scope.data.indexOf(item);
$scope.data.splice(index, 1);
};
hope this may help you
i am using titanium 3.3 and alloy 1.4.1. the user should be able to send an email to all selected people (those people are in an array called "contacts") from his phone's address book.
the user can select and deselect names/emails from his addressbook in a listview (yellow background in the linked screenshot).
screenshot:
http://s30.postimg.org/rsa82u9qp/listview_checkbox.png
the correct info (email) is pulled from the address book and added to the contacts array when one checks the checkbox. so selecting via the checkbox works, but when one deselects the checkbox the email/item is not removed from the array. see the last log entry line:
Ti.API.info(JSON.stringify(contacts) + " this is matches array at the
end");
the email which has been selected before and is now deselected is still in the contacts array.
i also found this, but it doesnt help unfortunately.
http://developer.appcelerator.com/question/163878/loop-through-listview-to-grab-items-with-certain-properties#comment-206400
the code:
$.listview.addEventListener('itemclick',function(e){
var item = e.section.getItemAt(e.itemIndex);
if (item.properties.accessoryType == Ti.UI.LIST_ACCESSORY_TYPE_NONE) {
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_CHECKMARK;
Ti.API.info(item.textEmail.text + " this is item.textEmail.textinside adding if");
var added = item.textEmail.text;
if (!_.contains(contacts,added)) {contacts.push(added);
}
Ti.API.info(JSON.stringify(added) + " item 1 added");
Ti.API.info(contacts + " this is matches array inside adding if");
}
else {
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_NONE;
var removed = item.textEmail.text;
contacts = _.without(contacts, removed);
//contacts.splice(removed);
Ti.API.info(JSON.stringify(removed) + " item 2 removed");
Ti.API.info(JSON.stringify(contacts) + " this is contacts in removing if case");
}
e.section.updateItemAt(e.itemIndex, item);
Ti.API.info(JSON.stringify(contacts) + " this is matches array at the end");
});
any ideas what im doing wrong here?
First you should have a flat Array (contacts):
var contacts = new Array();
...
Then add/remove textEmail.text properties and search them properly
if (item.properties.accessoryType == Ti.UI.LIST_ACCESSORY_TYPE_NONE)
{
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_CHECKMARK;
var i;
for(i in item.textEmail.text) //item.textEmail.text is Object
{
if(contacts.indexOf(item.textEmail.text[i]) === -1)
{
contacts.push(item.textEmail.text[i]);
Ti.API.info(item.textEmail.text[i] + " item added");
}
}
Ti.API.info(contacts + " this is matches array inside adding if");
}
else
{
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_NONE;
var i;
for(i in item.textEmail.text)
{
var p = contacts.indexOf(item.textEmail.text[i]);
if(p !== -1)
{
contacts.splice(p,1);
Ti.API.info(item.textEmail.text[i] + " item removed");
}
}
Ti.API.info(contacts + " this is contacts in removing if case");
}
// if item.textEmail.text is equal to Email Person Object:
{ "work" : ["...", "..."], "home" : ["...", "..."] }
var i, j;
for(i in item.textEmail.text)
{
for(j = 0; j < item.textEmail.text[i].length; j++)
{
// Start Add Code
if(contacts.indexOf(item.textEmail.text[i][j]) === -1)
{
contacts.push(item.textEmail.text[i]);
} // End Add Code
// Start Remove Code
var p = contacts.indexOf(item.textEmail.text[i]);
if(p !== -1)
{
contacts.splice(p,1);
} // End Remove Code
}
}
What I'd like to be able to do is make my function find the index of an array in my array list and delete it. I'd like it to find the first and last name of a person stored inside of an array stored in in it's two first slots (0 and 1) (ex: example[0]=["Robert", "Brown", 1000, 2100, 600, 400];) and delete it (the whole element[0]) from the list of my array. This is the list that I have right now:
voyageur[0]=["Roger", "Dagenais", 1000, 2100, 600, 400];
voyageur[1]=["Phil", "Thomas", 200, 300, 1400, 800];
voyageur[2]=["Nikolas", "Brideau", 1000, 2000, 3000, 5000];
Now let's say I want to delete Phil Thomas (element #1) from my array. How would I do it?
function supprimer(event:MouseEvent):void {
var indiceVoyageur:int;
var indiceVoyageurPrenom:int;
var indiceVoyageurNom:int;
if ( (boitePrenom.text != "") && (boiteNom.text != "") )
{
for (var rang:int = 0; rang < voyageur.length; rang++)
{
indiceVoyageurPrenom = (voyageur[rang][0].indexOf(boitePrenom.text));
indiceVoyageurNom = (voyageur[rang][1].indexOf(boiteNom.text));
if (indiceVoyageurPrenom != -1)
{
for (var i=indiceVoyageur; i <voyageur.length; i++)
{
voyageur[i] = voyageur[i+1];
}
voyageur.pop();
}
}
}
}
This is some code that I had made previously but it doesn't really work properly. If you have another way of doing what it is that I want to do, that would also be fine.
Any help is appreciated.
Instead of shuffling and popping, you can just use splice:
function supprimer(): void {
var indiceVoyageur: int;
var indiceVoyageurPrenom: int;
var indiceVoyageurNom: int;
if ((boitePrenom.text != "") && (boiteNom.text != "")) {
for (var rang: int = 0; rang < voyageur.length; rang++) {
indiceVoyageurPrenom = (voyageur[rang][0].indexOf(boitePrenom.text));
indiceVoyageurNom = (voyageur[rang][1].indexOf(boiteNom.text));
if (indiceVoyageurPrenom != -1 && indiceVoyageurNom != -1) {
voyageur.splice(rang, 1);
break;
}
}
}
}
I cannot understand exactly your code as it seems to be with some strange variables.. But this should work:
function clear(firstName:String, lastName:String):Boolean {
var total:uint = _users.length;
// _users is a member variable of the users array
// you can pass it to the function if you don't like it to be member
var found:Boolean;
for (var i:uint = 0; i < total; i++) {
var data:Object = _users[i];
if (data.indexOf(firstName) != -1 && data.indexOf(lastName) != -1) {
data.splice(i, 1);
i--; // keep searching for other items in the array
found = true;
}
}
return found; // return true if it finds it
}
this will satisfy your need as to delete those elements and returns the output. no need of looping. directly use array methods max for optimization.
var voyageur1:Array=["Roger", "Dagenais", 1000, 2100, 600, 400];
var voyageur2:Array=["Phil", "Thomas", 200, 300, 1400, 800];
var voyageur3:Array=["Nikolas", "Brideau", 1000, 2000, 3000, 5000];
var voyageur4:Array=voyageur2.splice(0,2);
trace(voyageur4); //Phil,Thomas
trace(voyageur2); //200,300,1400,800[after deleting].
hope you expected this.
I have an angular foreach loop and i want to break from loop if i match a value. The following code does not work.
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
How can i get this?
The angular.forEach loop can't break on a condition match.
My personal advice is to use a NATIVE FOR loop instead of angular.forEach.
The NATIVE FOR loop is around 90% faster then other for loops.
USE FOR loop IN ANGULAR:
var numbers = [0, 1, 2, 3, 4, 5];
for (var i = 0, len = numbers.length; i < len; i++) {
if (numbers[i] === 1) {
console.log('Loop is going to break.');
break;
}
console.log('Loop will continue.');
}
There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:
var keepGoing = true;
angular.forEach([0,1,2], function(count){
if(keepGoing) {
if(count == 1){
keepGoing = false;
}
}
});
please use some or every instances of ForEach,
Array.prototype.some:
some is much the same as forEach but it break when the callback returns true
Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.
Example for some:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.some(function (value, index, _ary) {
console.log(index + ": " + value);
return value === "JavaScript";
});
Example for every:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.every(function(value, index, _ary) {
console.log(index + ": " + value);
return value.indexOf("Script") > -1;
});
Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/
Use the Array Some Method
var exists = [0,1,2].some(function(count){
return count == 1
});
exists will return true, and you can use this as a variable in your function
if(exists){
console.log('this is true!')
}
Array Some Method - Javascript
As far as I know, Angular doesn't provide such a function. You may want to use underscore's find() function for this (it's basically a forEach which breaks out of the loop once the function returns true).
http://underscorejs.org/#find
If you use jQuery (hence not jqLite) in conjunction with AngularJS you can iterate with $.each - which allows breaking and continuing based on boolean return value expression.
JSFiddle:
http://jsfiddle.net/JEcD2/1/
Javascript:
var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
if (element === 'foo') {
return true; // continue
}
console.log(this);
if (element === 'bar') {
return false; // break
}
});
Note:
Though using jQuery is not bad, both native Array.some or Array.every functions are recommended by MDN as you can read at native forEach documentation:
"There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"
Following examples are provided by MDN:
Array.some:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true
Array.every:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
Concretely, you can exit of a forEach loop, and of any place, throw an exception.
try {
angular.forEach([1,2,3], function(num) {
if (num === 2) throw Error();
});
} catch(e) {
// anything
}
However, it is better if you use other library or implement your own function, a find function in this case, so your code is most high-level.
Try this as break;
angular.forEach([0,1,2], function(count){
if(count == 1){
return true;
}
});
As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use
jQuery.each ( array, function ( index, value) {
if(condition) return false; // this will cause a break in the iteration
})
See http://api.jquery.com/jquery.each/
Normally there is no way to break an "each" loop in javascript.
What can be done usually is to use "short circuit" method.
array.forEach(function(item) {
// if the condition is not met, move on to the next round of iteration.
if (!condition) return;
// if the condition is met, do your logic here
console.log('do stuff.')
}
break isn't possible to achieve in angular forEach, we need to modify forEach to do that.
$scope.myuser = [{name: "Ravi"}, {name: "Bhushan"}, {name: "Thakur"}];
angular.forEach($scope.myuser, function(name){
if(name == "Bhushan") {
alert(name);
return forEach.break();
//break() is a function that returns an immutable object,e.g. an empty string
}
});
You can use this:
var count = 0;
var arr = [0,1,2];
for(var i in arr){
if(count == 1) break;
//console.log(arr[i]);
}
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
console.log(index)
keepGoing = true;
ary.forEach(function(value, index, _ary) {
if(keepGoing){
if(index==2){
keepGoing=false;
}
else{
console.log(value)
}
}
});
});
$scope.arr = [0, 1, 2];
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
if ( $scope.arr[i] == 1 ) {
$scope.exists = 'yes, 1 exists';
break;
}
}
if ( $scope.exists ) {
angular.forEach ( $scope.arr, function ( value, index ) {
$scope.dict[index] = value;
});
}
I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.
I realise this is old, but an array filter may do what you need:
var arr = [0, 1, 2].filter(function (count) {
return count < 1;
});
You can then run arr.forEach and other array functions.
I realise that if you intend to cut down on loop operations altogether, this will probably not do what you want. For that you best use while.
This example works. Try it.
var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
if(i === 1){
break;
}
}
I would use return instead of break.
angular.forEach([0,1,2], function(count){
if(count == 1){
return;
}
});
Works like a charm.
Use Return to break the loop.
angular.forEach([0,1,2], function(count){
if(count == 1) {
return;
}
});
onSelectionChanged(event) {
let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
let selected_flag = 0;
selectdata.forEach(data => {
if (data.selected == true) {
selected_flag = 1;
}
});
if (selected_flag == 1) {
this.showForms = true;
} else {
this.showForms = false;
}
}
Just add $index and do the following:
angular.forEach([0,1,2], function(count, $index) {
if($index !== 1) {
// do stuff
}
}