I have a code as follow:
function getdata($scope){
$scope.todos = [
{name:"john",data:"1 2 3"},
{name:"Marry",data:"6 7 8"},
{name:"Edward",data:"2 4 5"}
];
var seri=new Array();
for(var item in $scope.todos)
{
seri.push(
{
name: item.name,
data: [1, 0, 4]
});
}
console.log(seri);
}
Now when I check the console for the name it returns undefined. what is the problem?
Try
function getdata($scope) {
$scope.todos = [
{ name: "john", data: "1 2 3" },
{ name: "Marry", data: "6 7 8" },
{ name: "Edward", data: "2 4 5" }
];
var seri = new Array();
angular.forEach($scope.todos, function (item, key) {
seri.push({
name: item.name,
data: [1, 0, 4]
});
});
console.log(seri);
//you can get data from this by using return
}
When you loop through an array in javascript the item is an integer with the position of the value in the array. You'll need to use this position to get the true item, like this:
for (var i in $scope.todos) {
var item = $scope.todos[i];
...
}
If the function is inside a controller and being called as such you should declare it as
$scope.getData = function() {
}
And then it should work fine. If the function is NOT to be part of the scope and you are passing the scope in then try receiving the parameter as "scope" and not "$scope" which has a special meaning in Angular.
this is not how you iterate array in javascript (see materik answer).
you can alternatively use angular.forEach to iterate the todos array like this:
angular.forEach($scope.todos, function(item)
{
seri.push(
{
name: item.name,
data: [1, 0, 4]
});
});
Related
I want to store the array values in an object like below:
{"newpublicareas":[{"area_name":"x",
"level":0}]}
This is what i have done:
getNewTopLevelS(res){
this.newpublicarea = []
res.map((j)=> {
this.newpublicarea.push(j.body.data.areas)
})
this.entireareas.push(this.newpublicarea)
}
But it is pushing in wrong format.
Any suggestions?
Check this,
var res = [{"area_name":"x","level":0},{"area_name":"y","level":4},]
var newpublicarea = {newpublicarea:[]}
res.map((j)=> {
newpublicarea.newpublicarea.push(j)
})
console.log(newpublicarea)
Gives
{
newpublicarea: [{
area_name: "x",
level: 0
}, {
area_name: "y",
level: 4
}]
}
https://jsfiddle.net/1ev6tq4w/
I got an array from database as
[
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
Now my required answer is that should be in the following format,
[["abc",100],
["xyz",150]]
But after some coding I got an array of Array as shown below in the console
[0:[0:"abc",1:100]
1:[0:"xyz",1:150]]
Before question down / marking duplicate please read my requirement, and if its there then mark it and please post that link as per my required solution so i can get my solution from there
So any help will be great help....
You can do like this:
data = [
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
var array =[]
data.forEach(function(item){
var tmpArray = []
tmpArray.push(item.id.unitno,item.amount)
array.push(tmpArray)
})
Now you will get your required data in the array.
I don't know how you got this below code, but that's invalid Array
[0:[0:"abc",1:100] 1:[0:"xyz",1:150]]
For your desired output you can do it with JavaScript, no need angular. Just run a simple for loop.
var temp1 = [{
id: {
unitno: 'abc'
},
amount: 100
}, {
id: {
unitno: 'xyz'
},
amount: 150
}];
var eee = [];
temp1.forEach(function(el) {
eee.push([el.id.unitno, el.amount])
});
console.log('eee:', eee);
Hope this is what you needed.
var arr = [{
id : { unitno: 'abc' },
amount: 100
},{
id : { unitno: 'xyz' },
amount: 150
}];
var result = [];
for (var i = 0; i < arr.length; i++) {
var newArray = [];
newArray.push( arr[i]["id"]["unitno"] );
newArray.push( arr[i]["amount"] );
result.push( newArray );
}
console.log( result );
I have an array (1) with some id's and another array (2) with creatures, they have id (like in first array) and names. And I want to create new array (it will be looks like (1) id array, but only with id that in (2)). So I think that I need use filter.
(1)
$scope.main = ['dog', 'cat', 'bird', 'bug', 'human'];
(2)
$scope.creatures = [
{
id: 'cat',
name : 'fluffy'
},
{
id: 'cat',
name : 'mr.Kitty'
},
{
id: 'human',
name: 'Rachel'
},
{
id: 'cat',
name : 'Lucky'
},
{
id: 'cat',
name: 'Tom'
}
];
filter:
$scope.results = $scope.main.filter(function(item) {
angular.forEach($scope.creatures, function(creature) {
return item === creature.id;
});
});
I expect that it will be
$scope.results === ['cat', 'human'];
But I have
$scope.results // [0] empty array
Where I'm wrong? Plnkr example
It is not working because you are returning in the first iteration itself inside forEach loop. You can get it working as shown below :
Updated Plunker
$scope.results = [];
$scope.main.filter(function(item) {
angular.forEach($scope.creatures, function(creature) {
if(item === creature.id){
if( $scope.results.indexOf(item) === -1){
$scope.results.push(item);
}
}
});
});
Instead of looping again inside the filter, we can get the ids out of creatures array first and then filter them in main array like below :
$scope.results = [];
$scope.ids = $scope.creatures.map(function (creature){
return creature.id;
});
$scope.ids.map(function (id){
if($scope.main.indexOf(id) !== -1){
if( $scope.results.indexOf(id) === -1){
$scope.results.push(id);
}
}
});
console.log($scope.results);
Made few changes in your plunker, it is working now. Can you check with this code.
var app = angular.module('App', []);
app.controller('Ctrl', function($scope, $timeout){
$scope.main = ['dog', 'cat', 'bird', 'bug', 'human'];
$scope.creatures = [
{
id: 'cat',
name : 'fluffy'
},
{
id: 'cat',
name : 'mr.Kitty'
},
{
id: 'human',
name: 'Rachel'
},
{
id: 'cat',
name : 'Lucky'
},
{
id: 'cat',
name: 'Tom'
}
];
var array = [];
$scope.call = function() {
angular.forEach($scope.main,function(item){
angular.forEach($scope.creatures, function(creature) {
if(item == creature.id){
// console.log('item',item,' creatureId',creature.id);
if(array.indexOf(item) < 0 ){
array.push(item);
}
console.log(array);
}
});
$scope.results = array;
});
};
$scope.call();
console.log('result ',$scope.results);
});
I need filter for ng-repeat, that explode elements in "general" array, if element exist in "suggest" array (by id field).
$scope.general= [{id: 21323, name: 'alex'}, {id: 8787, name: 'maria'}, {id: 8787, name: 'artem'}];
$scope.suggest = [{id: 21323, name: 'alex'}, {id: 8787, name: 'maria'}];
<div ng-repeat="elem in general">{{elem.name}}</div>
You should create your own custom filter and you'll probably want to use Array.prototype.filter.
You said you wanted to exclude by the property id. The following filler optionally allows specifying a property. If the property is not specified, then the objects are excluded by strict equality (the same method used by the ===, or triple-equals, operator) of the objects.
angular.module('myFilters', [])
.filter('exclude', function() {
return function(input, exclude, prop) {
if (!angular.isArray(input))
return input;
if (!angular.isArray(exclude))
exclude = [];
if (prop) {
exclude = exclude.map(function byProp(item) {
return item[prop];
});
}
return input.filter(function byExclude(item) {
return exclude.indexOf(prop ? item[prop] : item) === -1;
});
};
});
To use this filter in your html:
<div ng-repeat="elem in general | exclude:suggest:'id'">{{elem.name}}</div>
Here is an example jsfiddle:
https://jsfiddle.net/6ov1sjfb/
Note that in your question artem's id matches maria's thus both artem and maria were filtered. I changed artem's id in the plunker to be unique to show that the filter works.
Try this :
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.general = [{
id: 21323,
name: 'alex'
}, {
id: 8787,
name: 'maria'
}, {
id: 8787,
name: 'artem'
}];
$scope.suggest = [{
id: 21323,
name: 'alex'
}, {
id: 8787,
name: 'maria'
}];
$scope.filteredArray = function () {
return $scope.general.filter(function (letter) {
for (i = 0; i < $scope.suggest.length; i++) {
return $scope.suggest[i].id !== letter.id
}
});
};
}
and
<div ng-repeat="elem in filteredArray(letters)">{{elem.name}}</div>
check out the fiddle : http://jsfiddle.net/o2er6msv/
Note: please chk ur id, they are duplicated
I'm trying to use AngularJS for my first project (a tournaments manager) and the orderBy filter on ng-repeat doesn't work :( I have read all the documentation about that, but nothing to do :/
So, I have vars defined on $scope like that :
$scope.order_item = "count_win";
$scope.order_reverse = false;
$scope.teams = {
100 : {
id: 100,
name: "XXX",
count_win: 1,
count_loose: 2,
goal_average: 1,
},
200 : {
id: 200,
name: "XXX",
count_win: 1,
count_loose: 2,
goal_average: 1,
},
[...]
};
Now, on my view i'm trying to reorder (first with only one order item) but never work...
<tr ng-repeat="team in teams | orderBy:order_item:order_reverse">
<td>{{team.name}}</td>
<td>{{team.count_loose}}</td>
<td>{{team.goal_average}}</td>
</tr>
The second time, I want to reorder from 2 pieces of information: count_win and goal_average if first are equal.. I try to replace $scope.order_item like that, but if with one the code doesn't work, he'll never work with 2...
$scope.order_item = ['count_win','goal_average'];
Thank you all for reading and sorry for the post size.
$scope.teams isn't an array (it's an object of objects), and the orderBy filter only works with arrays. If you make $scope.teams an array, it will work:
$scope.teams = [
{
id: 100,
name: "team1",
count_win: 3,
count_loose: 2,
goal_average: 2,
},
{
id: 200,
name: "team2",
count_win: 3,
count_loose: 2,
goal_average: 1,
},
{
id: 300,
name: "team3",
count_win: 1,
count_loose: 2,
goal_average: 1,
}
];
Or, you can add a special filter that works on objects, like this (borrowed from here):
app.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
And use it like this:
<tr ng-repeat="team in teams | orderObjectBy:order_item:order_reverse">
Note that this custom filter will not work with an array of sort orders as in the second part of your question.
You don't have to create a scope parameter for your orderBy, you can directly do this in your markup if you are dealing with arrays.
<tr ng-repeat="team in teams | orderBy:count_win:false">
With two parameters, you should just do
<tr ng-repeat="team in teams | orderBy:['count_win','goal_average']">
After for a more complex order, you could create a function in your scope like so :
$scope.customOrder = function (team) {
//custom
}
And just call it like
<tr ng-repeat="team in teams | orderBy:customOrder">
Like #Jerrad said, ng-repeat only works with arrays, so you need to convert your teams object into an array to get it work properly.
ng-repeat works only on arrays, not on JSON objects.
This was already discussed here: Angular - Can't make ng-repeat orderBy work
You either have to change the JSON object to an Array, or to convert it on the fly.
The controller could then look like this:
var app = angular.module('app', []);
app.controller('Ctrl', function ($scope) {
$scope.teams = [
{
id: 100,
name: "A Team",
count_win: 1,
count_loose: 2,
goal_average: 1
},
{
id: 200,
name: "C Team",
count_win: 2,
count_loose: 3,
goal_average: 4
},
{
id: 300,
name: "B Team",
count_win: 4,
count_loose: 1,
goal_average: 8
}
];
$scope.predicate = 'name';
});
I created a fiddle here with a demo containing your data:
http://jsfiddle.net/c3VVL/