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

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);
});
});
}
});

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.

Limit angular ng-repeat to certain rows

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.).

How to implement multiple filters on model's array/content via checkbox

I am trying to implement multiple filters on the same model. The attributes I want to apply the filter are arrays.
//Exam Model
App.Exam = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
courses : DS.hasMany('course',{ async: true }),
});
//Course Model
App.Course = DS.Model.extend({
name: DS.attr('string'),
description:DS.attr('string'),
professors: DS.attr(),
subjects: DS.attr(),
languages: DS.attr(),
exam: DS.belongsTo('exam', { async: true })
});
In the ExamsExam route after the model is resloved I extract the data I want to apply the filter on.
App.ExamsExamRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('exam', params.exam_id).then(function (exam) {
console.log("found single exam", exam);
return exam;
});
},
afterModel: function(model, transition){
var self = this;
var professorList = [];
var subjectList = [];
var languageList = [];
var promise = new Ember.RSVP.Promise(function(resolve, reject){
var courses = model.get('courses');
courses.forEach(function(course){
self.store.find('course', course.get('id')).then(function(course){
var profs = course.get('professors');
var subjects = course.get('subjects');
var languages = course.get('languages');
profs.forEach(function(prof) {
if (professorList.indexOf(prof) === -1) {
professorList.pushObject(prof);
}
});
subjects.forEach(function(subject) {
if (subjectList.indexOf(subject) === -1) {
subjectList.pushObject(subject);
}
});
languages.forEach(function(language) {
if (languageList.indexOf(language) === -1) {
languageList.pushObject(language);
}
});
});
});
var data = {
professorList: professorList,
subjectList: subjectList,
languageList: languageList
};
resolve(data);
});
promise.then(function(data) {
console.log(data);
model.set('professorNameList', data.professorList);
model.set('subjectList', data.subjectList);
model.set('languageList', data.languageList);
});
}
});
And this is my template
<script type="text/x-handlebars" data-template-name="exams/exam">
<h2>Exam page</h2>
<div class="row">
<div class="col-md-3 well">
<ul class="list-group well">
{{#each course in model.languageList}}
<li class="">
<label>
{{input type='checkbox'}}
{{course}}
</label>
</li>
{{/each}}
</ul>
<ul class="list-group well">
{{#each prof in model.professorNameList}}
<li class="">
<label>
{{input type='checkbox'}}
{{prof}}
</label>
</li>
{{/each}}
</ul>
<ul class="list-group well">
{{#each subject in model.subjectList}}
<li class="">
<label>
{{input type='checkbox'}}
{{subject}}
</label>
</li>
{{/each}}
</ul>
</div>
<div class="col-md-9">
{{#each course in model.courses}}
<div class="well">
Course name - {{course.name}}<br>
Professors - {{course.professors}}<br>
Subjects - {{course.subjects}}
</div>
{{/each}}
</div>
</div>
</script>
Now how do I change the content of the model so that if a user selects the language filter, only the courses belong to that selected language must be displayed.
Plus if the user selects language and subjects filter, only the filters matching that criteria should be displayed.
There is very little documentation on filtering via checkbox in ember.
Someone please suggest/guide me on how to approach this problem and get a clean solution.
Here is the JS BIN DEMO for better illustration of what I want to achieve.
Building on #joostdevries's answer...
Using every() with a callback is a fine solution, but it "feels" a little complicated. What you are looking for is basically an intersect between the arrays. For example, common professors to both an array of selected professors and array of professors in the model. Ember provides just such function, called ... wait for it ... intersection (see here) :). It returns an array containing the elements common to both arrays or an empty (0 length) array if there are no common elements.
Here is the same filteredCourses property, using the intersection method.
filteredCourses: function() {
var selectedProfessors = this.get('selectedProfessors'),
selectedLanguages = this.get('selectedLanguages'),
selectedSubjects = this.get('selectedSubjects'),
courses = this.get('model.courses');
var intersectFn = Ember.EnumerableUtils.intersection;
return courses.filter(function(course) {
return intersectFn(course.get('professors') || [], selectedProfessors).length ||
intersectFn(course.get('languages') || [], selectedLanguages).length ||
intersectFn(course.get('subjects') || [], selectedSubjects).length;
});
}.property('selectedProfessors.length', 'selectedLanguages.length', 'selectedSubjects.length')
First, we alias the intersection function as follows:
var intersectFn = Ember.EnumerableUtils.intersection;
This step is purely cosmetic - I just don't feel like typing Ember.EnumerableUtils.intersection every time; instead I just want to type intersectFn. Then, I just use the function to see if the arrays intersect. If they do - the length of resulting array would be greater than 0, which evaluates to true; otherwise - the length is 0, which evaluates to false. The one last quirk in all of this is that sometimes the property will be undefined which messes up the intersection method. For such cases, I set the array to empty.
So, course.get('professors') || [] means, if professors property (array) is defined - use it; otherwise - use an empty array.
Working solution here
With store.filter, you have a callback function which returns a boolean that decides whether or not something matches the filter:
filteredCourses: function() {
return courses.filter(function(course) {
return selectedProfessors.every(function(prof) {
return course.get('professors').contains(prof);
}) && selectedLanguages.every(function(lang) {
return course.get('languages').contains(lang);
}) && selectedSubjects.every(function(subj) {
return course.get('subjects').contains(subj);
});
});
}.property()
Here's an updated JSBin: http://emberjs.jsbin.com/comosepuno/1/. The checkbox component is borrowed from https://github.com/RSSchermer/ember-multiselect-checkboxes

ng-repeat run as many times as integer parameter doesn't work in some cases

I want to run angular as many times as integer value passed to it.
EDIT: I simplified this example because originally I used function to return array based on number passed to it.
HTML
<body ng-app="userFilterModule">
<div class="container-fluid" ng-controller="UserfilterController as Ctrl">
<div class="row">
<div class="filter_tableTbody col-xs-12">
<div class="row filter_tableRow" ng-repeat="user in Ctrl.obj_users">
<!-- ... -->
<div class="col-xs-2">
<span class="filter_rateStars" ng-repeat="a in Ctrl.ratingArr| limitTo: user.rate">
★
</span>
<span class="filter_rateStars notActive" ng-repeat="a in Ctrl.ratingArr| limitTo: 5 - user.rate">
☆
</span>
</div>
</div>
</div>
</div>
</div>
</body>
And everything works fine if ratingArr contains numbers e.g.
app.controller('UserfilterController', function ($scope) {
this.int_male_counter = this.int_female_counter = 5;
this.str_sort_by = {
prop_name: 'f_name',
order: 'asc'
};
//problem starts here
this.ratingArr = [1,2,3,4,5];
this.obj_users = new Users(this.int_male_counter, this.int_female_counter).list;
this.fn_set_sorting = function (str) {
if (this.str_sort_by.prop_name === str) {
this.str_sort_by.order = this.str_sort_by.order === 'des' ? 'asc' : 'des';
} else {
this.str_sort_by.order = 'asc';
this.str_sort_by.prop_name = str;
}
this.obj_users.sortByObjKeyVal(this.str_sort_by.prop_name, this.str_sort_by.order);
};
this.fn_setlected_filter = function (str) {
return str === this.str_sort_by.prop_name;
};
this.fn_is_descending = function(){
return this.str_sort_by.order === 'des';
};
});
But when I change it to new Array(5) or ['','','','',''] or ['a','a','a','a','a']
I get error in console: Error: [ngRepeat:dupes] why?
Thanks!
By default, you cannot use identical values in the array processed by ng-repeat. Quoting the docs:
error:dupes
Duplicate Key in Repeater
Occurs if there are duplicate keys in an ngRepeat expression.
Duplicate keys are banned because AngularJS uses keys to associate DOM
nodes with items.
By default, collections are keyed by reference which is desirable for
most common models but can be problematic for primitive types that are
interned (share references).
As advised in the same docs, just use track by $index suffix (so that items will be keyed by their position in the array instead of their value) to resolve the issue:
<span class="filter_rateStars"
ng-repeat="a in Ctrl.ratingArr | limitTo: user.rate track by $index">

Categories

Resources