ANGULARJS ng-repeat - iterating with objects['propertyname'] - javascript

how do you ng-repeat object with property names such as
$scope.myobjects = [
{
'property1': {
id: 0,
name: 'somebody'
}
},
{
'property2': {
id: 1,
name: 'someguy'
}
}];

As the keys of the object is not same, you can't just iterate it. May be you can do it in this way:
DEMO
<div ng-repeat="object in myobjects">{{getValue(object,'id') }}
{{getValue(object,'name')}}
</div>
In your controller:
$scope.getValue = function(value,field) {
var key = Object.keys(value).filter(function(val)
{
return val != "$$hashKey"
})[0];
return value[key][field];
}

You have to add a nested ng-repeat too like below if you want to take property names of objects (second one is looping into the objects):
<div ng-repeat="(index, object) in myobjects">
<div ng-repeat="(key, value) in object">
<strong>key: </strong> {{ key }}, <strong>value: </strong>{{ value }}
<strong>value.id: </strong> {{ value.id }}, <strong>value.name: </strong>{{ value.name }}
</div>
</div>
This prints:
key: property1, value: {"id":0,"name":"somebody"} value.id: 0, value.name: somebody
key: property2, value: {"id":1,"name":"someguy"} value.id: 1, value.name: someguy
Demo: http://embed.plnkr.co/SIMjaXMZPzbHLOCYRU8T/preview

ng-repeat with obj prop
<div ng-app="demo" ng-controller="abc">
<div ng-repeat="(key, value) in myobjects">
<div ng-repeat="objProp in value">{{objProp.name}}</div>
</div>
</div>
var app = angular.module('demo', []);
app.controller('abc', function ($scope) {
$scope.myobjects = [{
'property1': {
id: 0,
name: 'somebody'
}
}, {
'property2': {
id: 1,
name: 'someguy'
}
}];
})
here is working jsfiddle

Related

Array with configured index does not work on ng-repeat nor display in html in AngularJS

I am trying to ng-repeat a configured $index of an array, but this seems to not work in my favor.
CONTROLLER.JS
let vm = this;
let obj = [
{
id: '12345-6789-10',
code: 'test1',
time_stamp: 15183626121
}, {
id: '12345-6789-11',
code: 'test2',
time_stamp: 15183626122
}
];
vm.stocks_code = [];
obj.map(r => stocks_code[r.id] = r.code);
console.log(vm.stocks_code) // OUTPUT: [12345-6789-10: "test1",
// 12345-6789-11: "test2"];
let test = [12345-6789-10: "test1", 12345-6789-11: "test2"] // obviously wont
// work because only `{}` can handles this syntax.
INDEX.HTML
<pre>
{{ vm.stocks | json }} // does not display
</pre>
<div ng-repeat="o in vm.stocks_code">
{{ $index }} : {{ o }} // does not display
</div>
Simply use ng-repeat:
angular.module("app",[])
.controller("ctrl", function() {
var vm = this;
vm.objArr = [
{
id: '12345-6789-10',
code: 'test1',
time_stamp: 15183626121
}, {
id: '12345-6789-11',
code: 'test2',
time_stamp: 15183626122
}
];
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl as vm">
<div ng-repeat="o in vm.objArr">
{{ $index }} : {{ o.id }} {{o.code}}
</div>
</body>

angularjs - Change the order of a list with update of the other list entries

I have a Key/Value List with 3 Entries, e.g.
0, Value1
1, Value2
2, Value3
3, Value4
If I change 2 to 0, the entry with index 2 should slip to the position 0 and the additional elements slip around a position to the back.
eg from 0-1-2-3 will then be 2-0-1-3
HTML
<div ng-controller="MyCtrl">
<div class="row-sort" ng-repeat="(key1, value1) in selectList">
<select class="row-select">
<option ng-repeat="(key2, value2) in selectList" value={{key2}} ng-selected="key1 == key2">{{key2}}</option>
</select>
<span class="row-label">{{value1.name}}</span>
</div>
</div>
JavaScript
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.selectList = [{
idx: 0,
name: 'Value1'
}, {
idx: 1,
name: 'Value2'
}, {
idx: 2,
name: 'Value3'
}, {
idx: 3,
name: 'Value4'
}]
}
JS Fiddle Link
EDIT 1: It sould work like the jQuery Sortable Plugin, but only with Select-Boxes ...
Jquery Sortable
Anyone a idea how getting this work properly and correct with AngularJS?
Its required for Angular UI Grid (Reorder Columns)
Thank you very much!
You can add to your list selected key to bind it to ng-models for select and use orderBy:
$scope.selectList = [{
idx: 0,
selected: '0',
name: 'Value1'
}, {
idx: 1,
selected: '1',
name: 'Value2'
}, {
idx: 2,
selected: '2',
name: 'Value3'
}, {
idx: 3,
selected: '3',
name: 'Value4'
}];
HTML
<div class="row-sort" ng-repeat="(key1, value1) in selectList | orderBy : 'selected'">
<select class="row-select" ng-model="value1.selected">
<option ng-repeat="(key2, value2) in selectList"
value={{key2}}>{{key2}}</option>
</select>
<span class="row-label">{{value1.name}}</span>
</div>
EDIT
You can write watcher and replace positions for your items:
$scope.$watch(function () {
return $scope.selectList;
},
function (newVal, oldVal) {
var selectedItemId;
var selected;
angular.forEach($scope.selectList, function(item){
if(item.idx !== parseInt(item.selected)){
selectedItemId = item.idx;
selected = item.selected;
}
});
angular.forEach($scope.selectList, function(item){
if(item.selected === selected){
item.selected = ''+selectedItemId;
item.idx = selectedItemId;
selectedItemId = undefined;
selected = undefined;
}
if(item.idx !== parseInt(item.selected)){
item.idx = parseInt(item.selected);
}
});
},true);
Demo Fiddle 2

How to filter values in ng-repeat by partial string property?

I have this controller with products and filterStr variables:
app.controller('FooCtrl', function($scope) {
$scope.products = [
{ id: 1, name: 'Michael', data: 'Berlin' },
{ id: 2, name: 'Maria', data: 'Moscow'}
{ id: 3, name: 'Alex', data: 'Aragon'},
{ id: 4, name: 'Mara', data:'Paris' }
/*... etc... */
];
$scope.filterStr = 'ar';
});
Here ng-repeat:
<div ng-repeat="product in products | filter: { name: filterStr }">
In ng-repeat above I want to display objects only that has inside name property this combination of letters ar:
id: 2, name: 'Maria', data: 'Berlin'
id: 4, name: 'Mara', data:'Paris'
What is the best way to implement the desired filter in angularjs?
You can try custom filter
<div ng-repeat="product in products | search:'name':'ar' ">
{{product.name}}
</div>
app.filter('search', function() {
return function(input,key,searchText) {
var out = [];
angular.forEach(input, function(obj) {
if(obj[key]){
var text = obj[key].search(searchText)
if(text > 0) {
out.push(obj);
}
}
});
return out;
}
});
First: Many thanks to #vignesh for a great answer! The code #vignesh provided encourage me to make such an implementation in my own project!
Second: While trying to implement this filter myself, I've noticed that this solution can be improved a little bit more...
app.filter('search', function()
{
return function(list, field, partialString)
{
// if the search string is invalid or empty - return the entire list
if (!angular.isString(partialString) || partialString.length == 0) return list;
var results = [];
angular.forEach(list, function(item)
{
if (angular.isString(item[field]))
{
if (item[field].search(new RegExp(partialString, "i")) > -1)
{
results.push(item);
}
}
});
return results;
}
});
I then used it with a search input and a repeater
<input ng-model="myPartialSearchString" />
<div ng-repeat="item in items | search:'name':myPartialSearchString ">
{{item.name}}
</div>
you can use the filter function from angular:
<input type="text" placeholder="Search" ng-model="search.$">
<input type="checkbox" ng-model="strict"> Exact match only
<div ng-repeat="product in products | filter: filter:search:strict">

Angular js filter array inside array

I am having a hard time doing an Angular filter to solve a problem as below.
The filter logic is as below:
1) If all listItem of that item has qtyLeft != 0, do not display that item
2) If any of the listItem of that item has qtyLeft == 0, display the item title as well as coressponding listItem that have qtyLeft == 0
Here's a basic example of my data structure, an array of items:
$scope.jsonList = [
{
_id: '0001',
title: 'titleA',
list: {
listName: 'listNameA',
listItem: [
{
name: 'name1',
qtyLeft: 0
},
{
name: 'name2',
qtyLeft: 0
},
]
}
},
{
_id: '0002',
title: 'titleB',
list: {
listName: 'listNameB',
listItem: [
{
name: 'name3',
qtyLeft: 2
},
{
name: 'name4',
qtyLeft: 0
},
]
}
},
{
_id: '0003',
title: 'titleC',
list: {
listName: 'listNameC',
listItem: [
{
name: 'name5',
qtyLeft: 2
},
{
name: 'name6',
qtyLeft: 2
},
]
}
},
]
Here is the final expected outcome:
<div ng-repeat="item in jsonList | filter: filterLogic">
<div> </div>
</div>
// final outcome
<div>
<div>Title: titleA, ListItem: Name1, Name2</div>
<div>Title: titleB, ListItem: Name4</div>
</div>
Created working Plunkr here. https://plnkr.co/edit/SRMgyRIU7nuaybhX3oUC?p=preview
Do not forget to include underscore.js lib in your project if you are going to use this directive.
<div ng-repeat="jsonItem in jsonList | showZeroElement track by $index">
<div>Title:{{ jsonItem.title}}, ListItem:<span ng-repeat="item in
jsonItem.list.listItem track by $index" ng-if="item.qtyLeft==0">
{{item.name}}</span>
</div>
</div>
And
app.filter('showZeroElement', function() {
return function(input) {
var items = []
angular.forEach(input, function(value, index) {
angular.forEach(value.list.listItem, function(val, i) {
var found = _.findWhere(items, {
'title': value.title
})
if (val.qtyLeft === 0 && found === undefined) {
items.push(value)
}
})
})
return items
}
})

how to execute function on ng-repeater running

Hi I have problem with ng-repeater in angular I want to execute function to do calculation on run my problem now the function is not execute when I pass the Id https://jsfiddle.net/gkqL3zdp/1/
can someone help me ?
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="category in model.categories"> <span> Category: {{ category.name }} </span>
<div ng-click="getID(category.Id)">
</div>
</div>
debugger;
angular.module("app", [])
.controller('ctrl', ['$scope',
function ($scope) {
$scope.model = {
categories: [{
"Id": 1,
name: '1'
}, {
"Id": 2,
name: '2'
},{
"Id": 3,
name: '3'
},{
"Id": 4,
name: '4'
}]
}
$scope.getID = function(id){
id=+2
console.log(parentId)
return result;
}
}])
You can use ng-init for that.
On the same div use something like:
<div ng-repeat="repeatExpression">
<div ng-init="getId()"></div>
</diV>
your clickable divs were 0 height and your parentId and result variables were undefined. I fixed in https://jsfiddle.net/gkqL3zdp/1/
$scope.getID = function(id){
console.log(id)
return id;
}

Categories

Resources