Limit angular ng-repeat to certain rows - javascript

For example if i had the json dataset here of all languages of books:
$scope.data = [{
"title": "Alice in wonderland",
"author": "Lewis Carroll",
"lang": ["en"]
}, {
"title": "Journey to the West",
"author": "Wu Cheng'en",
"lang": ["ch"]
}]
And I simply wanted to display exclusively english books, would I be able to do this purely using a filter in ng-repeat?
E.g.
<div ng-repeat="d in data | filter:d.lang='en'" style="margin-bottom: 2%">
{{d.title}}
</div>
I do not want to do it via any sort of form control (radio button etc). Would this be possible?
-EDIT- Thanks #GrizzlyMcBear for leading me down the right path! I got it to work with a slightly different filter function (which I'll paste below)
app.filter('MyFilter', function() {
var out = [];
angular.forEach(input, function(i) {
if (i.lang[0] === 'en') {
out.push(i);
}
})
return out;
}
});
and in the HTML
<div ng-repeat="d in data | MyFilter" style="margin-bottom: 2%">
{{d.title}}
</div>

Try like this
<div ng-repeat="d in data | filter: { lang : 'en'} " style="margin-bottom: 2%">
DEMO

You should use angular's filter,
I would also suggest that you use a function in the filter:
<div ng-repeat="item in collection | filter:filteringFunction" style="margin-bottom: 2%">
{{d.title}}
</div>
This way gives you more freeeeeedom (you're more than welcome to shout it Mel Gibson style ;-) )
in filtering your data by introducing more complex filtering logic.
var filteredLang = "en";
function filterByBookLanguage(collectionItem) {
var result = false;
if (collectionItem.lang[0] === filteredLang) {
result = true;
}
return result;
}
$scope.filteringFunction = filterByBookLanguage;
Now If you wish, you can also change the comperator function - filterByBookLanguage
(my terminology).
Say that your boss suddenly wants you to change the filtering logic from filtering books
into filtering by the author's name. Now all you have to do is add this condition:
if (bossWantsToChangeFilter) {
$scope.filteringFunction = filterByAuthorName;
} else {
$scope.filteringFunction = filterByBookLanguage;
}
All you have to remember is to write the comperator function with the current filtered item
as an argument and update the compared value of the language/author name
in the location you've found convenient ($scope, local variable, service etc.).

Related

Angular 1.5 filter with ng-repeat not working by track by id

so I tried so many different ways to get this done. Followed so many StackOverflow and could not get this to work. All I am trying to do is to filter some list items based on the value of a boolean property. Below is the picture of my object data. The closest example I am following is this question Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property. Still not working. does it have anything to do with an object literal and this type of filtering with property only works with array? I am new to javascript so not sure. Also using angular material, virtual repeat container and other material based things are not affecting the result, I can display the whole data, just the filtered by this specific property not working
loadAssets = () => {
var self = this;
self.infiniteAssets = {
numLoaded_: 0,
toLoad_: 0,
items: [],
pageNum:1,
virtualIndex:0,
getItemAtIndex: function (index) {
this.virtualIndex=index;
if (index > this.numLoaded_) {
this.fetchMoreItems_(index);
return null;
}
return this.items[index];
},
// Required.
getLength: function () {
if (this.virtualIndex > this.numLoaded_) {
return this.numLoaded_ ;
}else{
return this.numLoaded_ + 5 ;
}
},
fetchMoreItems_ : function (index) {
if (this.toLoad_ < index) {
self.loading = true;
this.toLoad_ += 20;
self.siAsset.getAssets(this.pageNum++,20)
.then(angular.bind(this, function (assets) {
//this.objLength = assets.length;
if(! assets.statusCode){
this.items = this.items.concat(assets);
this.toLoad_ = this.items.length;
this.numLoaded_ = this.toLoad_;
}
self.loading = false;
}))
}
}
};
console.log('++++++++++',self.infiniteAssets)
<md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">
<md-list>
<md-list-item class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets | filter: {disabled: true } track by asset.id" ng-click="$ctrl.loadDetail(asset)">
<span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
<p >{{asset.name}} </p>
<label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
<md-chips >
<md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
</md-chips>
</label>
<label ><i>{{asset.status || 'UNKNOWN'}}</i></label>
<md-button aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
<md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
</md-button>
<md-divider></md-divider>
</md-list-item>
</md-list>
</md-virtual-repeat-container>
Are you certain md-virtual-repeat works with filters? AngularJS Materials virtual repeat is a custom implementation of ng-repeat, so you can't expect it to work exactly as the original. Here's from the documentation.
Virtual repeat is a limited substitute for ng-repeat that renders only
enough DOM nodes to fill the container and recycling them as the user
scrolls.
Arrays, but not objects are supported for iteration. Track by, as
alias, and (key, value) syntax are not supported.
I would move the filtering inside your controller instead and just make sure the filter is reapplied whenever the collection changes.
As per you said, "Angular 1.5 filter with ng-repeat not working by track by id"
I have created sample example using AngularJs 1.5, and used filter with track by on ng-repeat.
angular.module('controllerAsExample', [])
.controller('SettingsController1', SettingsController1);
function SettingsController1() {
this.infiniteAssets = [
{disabled :false, name:'test0',id:234 },
{disabled :true, name:'test1',id:123 },
{disabled :false, name:'test2',id:345 }
];
//console.log(this.infiniteAssets);
}
<!doctype html>
<html >
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
</head>
<body ng-app="controllerAsExample">
<div ng-controller="SettingsController1 as settings">
<p>ng-repeat with track by field example using angularjs 1.5.0:</p>
<ul>
<li ng-repeat="asset in settings.infiniteAssets | filter: {disabled: false } track by asset.id">
{{asset.name}}
</li>
</ul>
</div>
</body>
</html>

Use angularjs nested ng-repeat to construct complex table

I'm having trouble making proper table with nested ng-repeat.
What I wanted is this https://jsbin.com/razamagabo/1/edit?output
but I'm stuck at here https://plnkr.co/edit/d5voXIpzYL81sSl9BSY2?p=preview
I don't mind my markup is not table but I'm still stuck with div
<div class="row">
<div class="col-xs-6" ng-repeat="obj in data">
{{obj.date}}
<div ng-repeat="user in obj.users">
<br>
{{user.name}}
<br>
{{user.mark}}
</div>
</div>
</div>
In order for you to be able to display your data in the desired way, it will probably be easiest if you restructure your data in the JS before trying to render it.
It will be very complicated to try and match on the user names when they are in separate objects in the data array.
I would suggest processing your scope.data in the controller. (I'm assuming that you don't have much control on how you are receiving the data).
For example after you get your data...
$scope.data = [
{
date:'1-1-2016',
users:[
{
'name':'james',
'mark':18
},
{
'name':'alice',
'mark':20
}
]
},
{
date:'2-1-2016',
users:[
{
'name':'james',
'mark':60
},
{
'name':'alice',
'mark':55
}
]
}
]
var userData = {};
var possibleDates = [];
for (dataObj of Object.entries($scope.data)) {
for (userObj of dataObj) {
if ( !userData[userObj.name] ) {
userData[userObj.name] = {};
}
userData[userObj.name][dataObj.date] = userObj.mark;
if (dates.indexOf(dataObj.date) < 0) {
dates.push(dataObj.date);
}
}
}
$scope.users = userData;
$scope.dates = possibleDates;
this will give you an object like this on your scope
$scope.users = {
'james': {
'1-1-2016': 18,
'2-1-2016': 60
},
'alice': {
'1-1-2016': 20,
'2-1-2016': 55
}
};
$scope.dates = ['1-1-2016', '2-1-2016'];
This to me seems easier to structure for your template. Though this assumes each user has an entry for each date.
<div>
<div id='header-row'>
<div id='empty-corner></div>
<div class='date-header' ng-repeat='date in $scope.dates></div>
</div>
<div class='table-row' ng-repeat='{key, value} in $scope.users'>
<div class='user-name'>{{ key }}</div>
<div class='user-data' ng-repeat='date in $scope.dates>
{{ value[date] }}
</div>
</div>
</div>
As long as you apply inline-block styles to the rows/elements this should give you what you are looking for.
Though you can also think of ways to simplify your data even further. You could instead of having each user have an object where the dates are keys, you could just push the values into an array.
With your current data structure it is not possible to display it like you want. You are trying to loop over date-users objects in data array but then you want to display user from inside users array in separate rows. With ng-repeat you can loop through rows tr but not through columns. First you would need to map your data array to group elements that are supposed to be visible in 1 row into 1 object in array. Currently you have them in 2 separate objects:
James mark: 18 and James mark: 60.

How to sort JSON data in ng-repeat?

I am getting a server response and binding these data to view using ng-repeat. Now I want to sort these data by priceList and name. I am able to sort name using orderBy, but not with priceList. I want to sort the products based on priceList. Sorting with name will change the order of list while sorting by priceList will effect only the order of products of each category. It will effect the order of displayed category. Please help me resolve this.
My code:
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}};</pre>
<hr/>
<table class="friend">
<tr>
<th>Name
</th>
<th><a href="" ng-click="predicate = 'priceList'>price</a></th>
</tr>
</table>
<div ng-repeat="data in _JSON[0].categories | orderBy:predicate">
<div ng-repeat="vals in data.itemTypeResults |orderBy:'partTerminologyName'" id="{{vals.partTerminologyName}}">
`<h4 style="background-color: gray">{{vals.partTerminologyName}} : Position :{{vals.position}}</h4>`<br>
<div ng-repeat="val in vals.products">
<b> Quantity:{{val[0].perCarQty}}</b><br>
<b> part:{{val[0].partNo}}</b><br>
<b>sku:{{val[0].sku}}</b><br>
<b> qtyInStock:{{val[0].qtyInStock}}</b><br>
<b> priceList:{{val[0].priceList}}</b><br>
<b>priceSave:{{val[0].priceSave}}</b><br>
<b> qtyDC:{{val[0].qtyDC}}</b><br>
<b> qtyNetwork:{{val[0].qtyNetwork}}</b><br>
<b> priceCore:{{val[0].priceCore}}</b><br>
</div>
</div>
</div>
JS:
$scope._JSON = [
{"categories":
[
{"id":14061,"name":"Drive Belts",
"itemTypeResults":[
{"partTerminologyName":"Serp. Belt",
"position":"Main Drive",
"products":{
"5060635":[
{"perCarQty":2,"partNo":"5060635",
"sku":"20060904","qtyInStock":2,"qtyNetwork":4,
"qtyDC":6,"priceList":19.15,"priceSave":3.29,
"priceCore":10.0}
],
"635K6":[
{"perCarQty":9,"partNo":"635K6",
"sku":"10062449","qtyInStock":2,"qtyNetwork":4,
"qtyDC":6,"priceList":18.15,"priceSave":3.21,"priceCore":10.0}
]
}
}
]
},
{"id":2610,"name":"Drive Belt Tensioners, Idlers, Pulleys & Components",
"itemTypeResults":[
{"partTerminologyName":"Drive Belt Tensioner Assembly",
"position":"N/A",
"products":{
"950489A":[
{"perCarQty":4,"partNo":"950489A",
"sku":"10150833","qtyInStock":2,"qtyNetwork":4,
"qtyDC":6,"priceList":18.15,"priceSave":3.21,"priceCore":10.0
}
]
}},
{"partTerminologyName":"Drive Belt Idler Pulley","position":"N/A",
"products":{
"89161":[
{"perCarQty":1,"partNo":"89161",
"sku":"99995959","qtyInStock":2,"qtyNetwork":4,
"qtyDC":6,"priceList":17.15,"priceSave":3.21,"priceCore":10.0}
],
"951373A":[
{"perCarQty":2,"partNo":"951373A","pla":"LTN",
"plaName":"Litens",
"sku":"10150926","qtyInStock":2,"qtyNetwork":4,
"qtyDC":6,"priceList":18.15,"priceSave":3.21,"priceCore":10.0}
]
}
}
]
}
]
}
];
$scope.predicate = '';
Fiddle: Fiddle
You might need to define a very good sorter function, or sort your products before they are interpreted by ng-repeat. I've created sorter function using underscore.js (or lodash).
You can checkout the demo (or the updated demo). Products are first sorted by category and then sorted by price in every category.
<!-- in html -->
<button ng-click="sortFn=sortByPrice">Sort By Price</button>
<button ng-click="sortFn=doNotSort">Do not Sort</button>
...
<div ng-repeat="val in sortFn(vals.products)">
...
// in js
$scope.sortByPrice = function(products) {
return _.sortBy(products, function(product) {
return product.length > 0 ? product[0].priceList : 0;
});
};
$scope.doNotSort = function(products) {
return products;
};
$scope.sortFn = $scope.doNotSort; // do not sort by default
BTW: You are directly calling val[0], which is very dangerous, if the product does not contain any elements, your code will break. My code won't ;-)
Update 1
The author asks me for a more pure Angular way solution.
Here is my answer: I think my solution is exactly in Angular way. Usually you can implement a filter (similar to orderBy) which wraps my sortByPrice. Why I don't do that, because you have ng-click to switch your order filter. I'd rather put control logic into a controller, not as pieces into view. This will be harder to maintain, when your project keeps growing.
Update 2
Okay, to make the +50 worthy, here is the filter version you want, (typed with my brain compiler) Please check in fiddle
You need to organize the products in other estructure. For example:
$.each($scope._JSON[0].categories , function( i , e) {
$.each(e.itemTypeResults, function(sub_i,sub_e) {
$.each(sub_e.products, function(itemTypeResults_i,product) {
console.log(product);
var aProduct = new Object();
aProduct.priceList = product[0].priceList;
aProduct.name = e.name;
$scope.products.push(aProduct);
});
} )
});
The code is not very friendly but what i do is putt all the products in one array so they can be ordered by the price. You have the products inside categories so that's why angular is ordering by the price in each category.
Fiddle:
http://jsfiddle.net/7rL8fof6/1/
Hope it helps.
Your fiddle updated: http://jsfiddle.net/k5fkocby/2/
Basically:
1. Digested the complex json object into a flat list of objects:
var productsToShow = [];
for (var i=0; i < json[0].categories.length; i++){
var category = json[0].categories[i];
for (var j=0; j<category.itemTypeResults.length;j++){
var item = category.itemTypeResults[j];
var products = item.products;
for (var productIndex in products) {
var productItems = products[productIndex];
for (var k=0; k<productItems.length;k++){
var productItem = productItems[k];
// Additions:
productItem.categoryName = category.name;
productItem.partTerminologyName = item.partTerminologyName;
productItem.position = item.position;
productsToShow.push(productItem);
}
}
}
}
Show category title only when needed by:
ng-repeat="product in (sortedProducts = (productsToShow | orderBy:predicate))"
and
ng-show="sortedProducts[$index - 1].partTerminologyName != product.partTerminologyName"
you can sort from your database and get final JSON data..
db.categories.aggregate([{$group : {category : {your condition} }, price: {$sort : { price: 1 } },}}])

collect filtered ng-repeat data to use in controller

I am trying to build a picture library in a responsive grid with data coming down from a Mongo DB. Data from db is in this form. name, image, keyword, bio, reference", searchable,
I start with an ng-repeat to display category selection checkboxes based on the picture keywords. This seems to work fine.
p CATEGORIES:
span.formgroup(data-ng-repeat='category in mongoController.catData')
input.checks( type='checkbox', ng-model='mongoController.filter[category]')
| {{category}}
Here is the factory that sorts and identifies the keyword checkboxes:
getCategories: function (cat) {
return (cat || []).map(function (pic) {
return pic.keyword;
}).filter(function (pic, idx, array) {
return array.indexOf(pic) === idx;
});
}
From there I filter an ng-repeat to display pictures based on the checkbox selection, and/or a search field which works well also.
input.form-control.input-med(placeholder="Search" type='text', ng-model="search.searchable")
br
div.light.imageItem(data-ng-repeat="picture in filtered=( mongoController.allData | filter:search | filter:mongoController.filterByCategory)")
a(data-toggle="modal", data-target="#myModal", data-backdrop="static", ng-click='mongoController.selectPicture(picture)')
img( ng-src='../images/{{picture.image}}_tn.jpg', alt='Photo of {{picture.image}}')
p Number of results: {{filtered.length}}
Functions to display picture lists:
//Returns pictures of checkboxes || calls the noFilter function to show all
mongoController.filterByCategory = function (picture) {
return mongoController.filter[picture.keyword] || noFilter(mongoController.filter);
};
function noFilter(filterObj) {
for (var key in filterObj) {
if (filterObj[key]) {
return false;
}
}
return true;
}
If you click one of the pictures a modal box pops up with all of the input fields where you can edit image specific fields.
The part I am really struggling with is how to gather the usable data from the filtered ng-repeat to use in the controller so when the modal box is up I can scroll right or left through the other pictures that met the criteria of the search.
Any suggestions would help, even why the hell are you doing it this way?
When you declare the ng-repeat that filters the pictures, your filtered variable belongs to the current $scope (which I cannot infer from the question, as it stands). You could associate the filtered variable to a specific controller by using Controller As syntax: (i.e. using <elem ng-repeat="picture in ctrl.filtered = (ctrl.data | filter1 | filterN)"/>)
Example: (also in jsfiddle)
var mod = angular.module('myapp', []);
mod.controller('ctrl', function() {
var vm = this;
vm.data = ['alice', 'bob', 'carol', 'david', 'ema'];
vm.onbutton = function() {
// access here the filtered data that mets the criteria of the search.
console.log(vm.filtered);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="ctrl as vm">
<input ng-model="search" type="text" />
<p data-ng-repeat="item in vm.filtered = (vm.data | filter:search)">
{{item}}
</p>
<p>Items: {{vm.filtered.length}}</p>
<button ng-click="vm.onbutton()">Show me in console</button>
</div>

How do I output a specific nested JSON object in Angular?

I'm a rank newbie to Angular, and I'm attempting to port an old jQuery-based app to NG. The JSON I'm starting with (parsed from an XML file) looks like this:
{
"setUps":{
"cartImage":
{
"_cartIm":"addtocart.gif",
"_cartIm_o":"addtocart.gif"
}
,"_supportImsPath":"/"
},
"product":
{
"matrix":
{
"thumbnails":[
{
"_myLabel":"Antique Brass Distressed",
"_thumbImage":"3",
"_cartCode":"160"
},
{
"_myLabel":"Antique Brass Light",
"_thumbImage":"156",
"_cartCode":"156"
},
{
"_myLabel":"Old Iron",
"_thumbImage":"ap",
"_cartCode":"157"
},
{
"_myLabel":"Oil-Rubbed Bronze",
"_thumbImage":"ob",
"_cartCode":"3"
}
],
"_myLabel":"Finishes"
},
"_Title":"Flower Cabinet Knob",
"_itNum":"100407x"
}
}
What I need to do with this is output specific elements on my template - first and foremost, the matrix object with its associated thumbnails. In this example, there is only one matrix, but for many of the products there are multiples, each with their own thumbnail arrays.
This is the controller:
var XMLt = angular.module("XMLtest",[]);
XMLt.factory("Xfactory",function($http){
var factory = [];
factory.getXML = function(){
return $http.get(productXML);
}
return factory;
});
XMLt.controller("Xcontroller",function($scope,Xfactory) {
$scope.Xcontroller = [];
loadXML();
function loadXML() {
Xfactory.getXML().success(function (data) {
var x2js = new X2JS();
prodData = x2js.xml_str2json(data);
$scope.thisItem = prodData.contents;
$scope.matrices = [];
angular.forEach($scope.thisItem.matrix,function(value,key)
{
$scope.matrices.push(value,key);
});
});
}
});
And this is my view template:
<div ng-controller="Xcontroller">
<h2>Title: {{ thisItem.product._Title }}</h2>
<div ng-repeat="thisMatrix in thisItem.product" class="matrix">
{{ thisMatrix._myLabel }}
</div>
</div>
My problem is that this ng-repeat, not surprisingly, returns a div for every child element of the product that it finds, not just the matrix. So I wind up with a couple of empty divs (for _Title and _itNum) in addition to the matrix div.
I've seen quite a few examples of filtering by comparing value literals, but they don't seem to apply in this case. I also tried writing a custom filter:
$scope.isObjType = function(input) {
return angular.isObject(input);
};
<div ng-repeat="thisMatrix in thisItem.product | filter:isObjType(matrix)">
That seemed to have no effect, still returning the extraneous divs. I can't seem to wrap my head around how I'd limit the repeat to a specific object type. Am I thinking of this the completely wrong way? If so, I'd welcome any input.
Since you only have one matrix, you don't need the repeat for the matrix label. You only need it for the thumbnails.
<div ng-controller="Xcontroller">
<h2>Title: {{ thisItem.product._Title }}</h2>
<div class="matrix">
{{ thisItem.product.matrix._myLabel }}
<div ng-repeat="thisThumbnail in thisItem.product.matrix.thumbnails" class="thumbnail">
{{thisThumbnail._myLabel}}
</div>
</div>
</div>
If it were possible to have multiple matrixes, the object would need to be modified to be able to represent that (by wrapping the matrix object in an array.)
Update per comments:
If you have the possiblity of multiple matrixes, you will need to modify the object to ensure that it is consistent when there is 1 vs when there are 2+.
<div ng-controller="Xcontroller">
<h2>Title: {{ thisItem.product._Title }}</h2>
<div ng-repeat="thisMatrix in thisItem.product.matrix" class="matrix">
{{ thisMatrix._myLabel }}
<div ng-repeat="thisThumbnail in thisMatrix.thumbnails" class="thumbnail">
{{thisThumbnail._myLabel}}
</div>
</div>
</div>
and in controller:
XMLt.controller("Xcontroller",function($scope,Xfactory) {
$scope.Xcontroller = [];
loadXML();
function loadXML() {
Xfactory.getXML().success(function (data) {
var x2js = new X2JS();
prodData = x2js.xml_str2json(data);
// must always have an array of matrixes
if (!prodData.contents.product.matrix.slice) {
prodData.contents.product.matrix = [prodData.contents.product.matrix];
}
$scope.thisItem = prodData.contents;
$scope.matrices = [];
angular.forEach($scope.thisItem.matrix,function(value,key)
{
$scope.matrices.push(value,key);
});
});
}
});

Categories

Resources