AngularJS displaying hierarchical data - angularjs

I'm trying to display a list of data in a hierarchical view.
My data looks something like this:
items:[
{
"model_id": "1",
"model_type_id": "1",
"name": "Parent 1",
"model_parent_id": ""
},
{
"model_id": "2",
"model_type_id": "1",
"name": "Parent 2",
"model_parent_id": ""
},
{
"model_id": "3",
"model_type_id": "2",
"name": "Child 1",
"model_parent_id": "1"
},
{
"model_id": "4",
"model_type_id": "2",
"name": "Child 2",
"model_parent_id": "2"
}
]
My controller looks like:
myApp.controller('ModelController', ['$scope', 'ModelFactory',
function ($scope, ModelFactory) {
$scope.init = function (id) {
$scope.brandId = id;
getModels($scope.brandId);
};
function getModels(brandId) {
ModelFactory.GetModels(brandId)
.success(function (mdls) {
$scope.models = mdls;
console.log($scope.mdls);
})
.error(function (error) {
$scope.status = 'Unable to load model data: ' + error.message;
console.log($scope.status);
});
};
}
]);
My HTML looks like:
<div ng-controller="ModelController" ng-init="init(brand.ID)">
<ul ng-sortable class="block__list block__list_words">
<li ng-repeat="model in models | filter: {model_type_id:1} ">{{model.model_name}} - {{model.model_id}}
<div ng-controller="ModelController" ng-init="init(brand.ID)">
<ul ng-sortable class="block__list block__list_words">
<li ng-repeat="m in models | filter: {model_type_id:2} | filter:{model_parent_id:model.model_id}">
{{m.model_name}} - {{m.model_parent_id}}
</li>
</ul>
</div>
</li>
</ul>
</div>
The filter isn't working where I'm trying to filter on the inner controller with the outer controller. I'm getting both children displayed below each parent. How can I get it so the parent is displayed, and only the children are displayed where the childs model_parent_id equals the model_id of the parent?

While I'm not sure whether there is a way to achieve this using filter, the normal way to display nested data is to reorganize the data structure to reflect what you want to display.
items:[
{
"model_id": "1",
"model_type_id": "1",
"name": "Parent 1",
"children": [{
"model_id": "3",
"model_type_id": "2",
"name": "Child 1"
}]
},
{
"model_id": "2",
"model_type_id": "1",
"name": "Parent 2",
"children": [{
"model_id": "3",
"model_type_id": "2",
"name": "Child 2"
}]
}
]
And then display them using nested ng-repeat
<ul>
<li ng-repeat="parent in items">
{{parent.name}} - {{parent.model_id}}
<ul>
<li ng-repeat="child in parent.children">
{{child.name}} - {{child.model_id}}
</li>
</ul>
</li>
</ul>
Note: There is no need to use nested controllers, just one on the top layer should be enough. If you need to use some shared logic recursively, use a custom directive to replace the li.
To reorganize the data you can do either on the server side or client side.
The following shows how to do in client side as we might not have the permission to change the server side API.
$scope.data = [];
angular.forEach(items, function(item) {
if (item.model_parent_id == "") {
$scope.data.push(item);
}
});
// add all parents first in case some children comes before parent
angular.forEach(items, function(item) {
if (item.model_parent_id == "") continue;
// search for parent
angular.forEach($scope.data, function(parent) {
if (parent.model_id == item.model_parent_id) {
if (!parent.children) parent.children = [];
parent.children.push(item);
}
}
});

Related

AngularJS Filed nested array of objects with array of objects

I'm trying to filter a nested array of objects with my own objects, by idSubject. But I'm not getting the right result.
I have articles (which have subjects)
And a array of objects (which are the subjects I want to filter the articles with)
Data looks like this:
So I'm trying to filter the array of articles by its subjects.
I tried the following:
<div class="panel panel-default"
ng-repeat="searchArticle in searchArticles | filter: {subjects: filterSubjects} as articleSearchResult">
So filterSubjects is the second screenshot and SearchArticles is the first screenshot.
Without much luck.
Hope you can help, please tell me if things are still unclear.
This custom filter will help you.
Example : http://plnkr.co/edit/jMizCLxPH6DtDA5wL15Q?p=preview
HTML:
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<h2>Select Subjects</h2>
<div ng-repeat="subject in subjects">
<label>
<input type="checkbox" ng-model="filterSubjects[subject.id]" ng-true-value="'{{subject.id}}'" ng-false-value="''">{{subject.name}}</label>
</div>
<h2>Filtered Articles</h2>
<div ng-repeat="searchArticle in searchArticles | subjectFilter:filterSubjects">{{searchArticle.name}}</div>
</div>
</body>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.searchArticles = [{
"name": "Article1",
"sid": "1"
}, {
"name": "Article2",
"sid": "1"
}, {
"name": "Article3",
"sid": "2"
}];
$scope.subjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject2",
"id": "2"
}];
$scope.filterSubjects = [];
});
app.filter('subjectFilter', function() {
return function(articles, filterSubjects) {
filtered = articles.filter(function(e){return filterSubjects.indexOf(e.sid) >= 0},filterSubjects);
return filtered;
}
});
if you want to filter based on object :
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.searchArticles = [{
"name": "Article1",
"sid": "1"
}, {
"name": "Article2",
"sid": "1"
}, {
"name": "Article3",
"sid": "2"
}];
$scope.subjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject2",
"id": "2"
}];
$scope.filterSubjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject1",
"id": "2"
}];
});
app.filter('subjectFilter', function() {
return function(articles, filterSubjects) {
var sFiltered = [];
for (var i = 0; i < filterSubjects.length; i++) {
sFiltered.push(filterSubjects[i].id);
}
var filtered = articles.filter(function(e) {
return sFiltered.indexOf(e.sid) >= 0;
}, sFiltered);
return filtered;
}
});

angular.forEach() not working

Hi friend I'm beginner in angular and getting stuck by using angular.forEach() function. I just want to call data from a nested array in data.json file. Please check my code below... ****I want to call data from --users-- key****
HTML
<div class="user-container" ng-controller="users">
<ul class="list">
<li ng-repeat="(key, value) in items">
{{key}} <p> {{value}}
</li>
</ul>
</div>
Problems with current code
When run my code in browser Its giving me only 2 <li> in ng-repeat then in {{Key}} I'm getting 0 in first <li> and 1 in second <li>
and in {{value}} I'm getting whole user list in first <li> and in second <li> their is no data
data.json
{
"data": {
"new": true,
"show_page": false,
"status": "signedin",
"users": [{
"Michele": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
"Gerry": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
}]
},
"success": true
}
Controller.js
var myApp = angular.module('app', []);
myApp.service('userData', ['$http', function($http){
return{
userslist : function(){
return $http({'url' : 'data.json', 'method' : 'GET'}).then(function(response){
return response.data;
}, function(data){
console.log(data)
})
}
}
}]);
myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
//var provideDataKey = Object.keys(data.users)[0];
$scope.items = [];
angular.forEach(data, function(item){
//console.log(item.users);
$scope.items.push(item.users)
})
console.log($scope.items)
})
}]);
response is the HTTP response, with its body (data), headers, etc.
So response.data is the body, which looks like this:
{
"data": {
"new": true,
"show_page": false,
"status": "signedin",
"users": [{
"Michele": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
"Gerry": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
}]
},
"success": true
}
What you want is to access the users field of the data field of this body. So what you want is
userData.userslist().then(function(data){
$scope.items = data.data.users;
console.log($scope.items)
})
$scope. items is an array, not an object. You want to display the elements of this array. So the syntax is:
{{ user }}
Your JSON is awful, because each user is an object with a single field, and you have no way of knowing the name of that field. You'd better change it to
"users": [
{
"name": "Michele",
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
{
"name": "Gerry",
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
]
That way you could just do:
<li ng-repeat="user in items">
{{ user.name }}, active since {{ user.active_since }}.
use this
myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
//var provideDataKey = Object.keys(data.users)[0];
$scope.items = [];
angular.forEach(data.users[0], function(item){
$scope.items.push(item);
})
console.log($scope.items)
})
}]);
you were iterating over data and not on users.

Bind scope property to tab title

I am new to angularJS and I am having trouble with binding properties of scope so two way binding can work properly. I am using sample code to generate tabs.
<div ng-app="SampleApp">
<div id="tabs" ng-controller="GridController as gridcon">
<ul>
<li ng-repeat="tab in tabs"
ng-class="{active:isActiveTab(tab.url)}"
ng-click="onClickTab(tab)">{{tab.title}}</li>
</ul>
<div id="mainView">
<div ng-include="currentTab"></div>
</div>
<input type="button" ng-click="changedata()" value="Check" />
</div>
</div>
Now my scope have two observable arrays and I want to show count of those arrays in tab title. I am using following code for controller.
var appRoot = angular.module('SampleApp', ["kendo.directives"]);
appRoot.controller('GridController', ['$scope', function ($scope) {
$scope.data1 = new kendo.data.ObservableArray([
{
issueId: 1,
issue: "County Incorrect"
},
{
issueId: 2,
issue: "City Incorrect"
},
{
issueId: 3,
issue: "Name Incorrect"
}
]);
$scope.data2 = new kendo.data.ObservableArray([
{
"id": 11,
"first_name": "James",
"last_name": "Butt",
"company_name": "Benton, John B Jr",
"address": "6649 N Blue Gum St",
"city": "New Orleans",
"county": "Bridgepoort",
"state": "LA",
"zip": 70116,
"phone1": "504-621-8927",
"phone2": "504-845-1427",
"email": "jbutt#gmail.com",
"web": "http://www.bentonjohnbjr.com"
},
{
"id": 12,
"first_name": "Josephine",
"last_name": "Darakjy",
"company_name": "Chanay, Jeffrey A Esq",
"address": "4 B Blue Ridge Blvd",
"city": "Brighton",
"county": "Livingston",
"state": "MI",
"zip": 48116,
"phone1": "810-292-9388",
"phone2": "810-374-9840",
"email": "josephine_darakjy#darakjy.org",
"web": "http://www.chanayjeffreyaesq.com"
}
]);
$scope.tabs = [{
title: 'Issue List (0)'.replace("0", $scope.data1.length),
url: 'tab1.html'
}, {
title: 'Corrected (0)'.replace("0", $scope.data2.length),
url: 'tab2.html'
}];
$scope.currentTab = 'tab1.html';
$scope.onClickTab = function (tab) {
$scope.currentTab = tab.url;
}
$scope.isActiveTab = function (tabUrl) {
return tabUrl == $scope.currentTab;
}
$scope.changedata = function () {
$scope.data1.pop();
$scope.data2.pop();
console.log($scope.data1.length);
console.log($scope.data2.length);
}
}]);
Now this works fine when you are loading page for first time. Now on a button click ("Check" button), I am modifying the arrays. What should I do so that tab title is always in sync with length of arrays ? I have tried observable objects but unless I am using binding in view, they will just notify the event. Is there no other way except handling change event of observable arrays ?
you can Copy this piece of code inside the $scope.changedata function.
$scope.tabs = [{
title: 'Issue List (0)'.replace("0", $scope.data1.length),
url: 'tab1.html'
}, {
title: 'Corrected (0)'.replace("0", $scope.data2.length),
url: 'tab2.html'
}];
Also it remains outside as well.

Angular JS orderBy not working using dropdown

i am trying to do orderBy using dropdown value, but its not working :(
CODE:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.datas = [{
"id": "1",
"name": "name area 1"
}, {
"id": "2",
"name": "name area 2"
}, {
"id": "3",
"name": "name area 3"
}, {
"id": "4",
"name": "name area 4"
}];
$scope.dropdown = [{
"title": "Newest first",
"value": "true"
}, {
"title": "Oldest first",
"value": "reverse"
}];
});
HTML:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul ng-repeat="rows in datas | orderBy: 'id':orderByData">
<li>{{rows.id}} : {{rows.name}}</li>
</ul>
<select ng-model="orderByData" ng-options="x.value as x.title for x in dropdown"></select>
</div>
</div>
DEOM JS BIN
Why you use reverse?
Please use false instead reverse and it should work fine.
$scope.dropdown = [{
"title": "Newest first",
"value": "true"
}, {
"title": "Oldest first",
"value": "false"
}];
You don't need reverse parameter here. Instead you can do something like this:
<ul ng-repeat="rows in datas | orderBy: getSort()">
<li>{{rows.id}} : {{rows.name}}</li>
</ul>
Where getSort is defined as:
$scope.getSort = function() {
return $scope.orderByData ? 'id' : '-id';
};
Basically you want sort part to look like orderBy: 'id' or orderBy: '-id'.
Demo: http://jsbin.com/pepureta/1/edit?html,js,output

multiselect treeview in backbone

I'm new to backbone and trying to establish some good paradigms.
Right now, I'm working on a search heavy site. There are dozens of attributes to search on, many are min max type, but 6 or so are multi select. Prior to backbone, I was using something called listtree to make a collapsible listtree for the multiselect options. I'm still going to use those css classes, but now I'm trying to use backbone with models and views. TBH, this seems like more work than just using straight jquery, so maybe I'm missing something.
My question is, how should I structure the models and the views for several multiselect widgets in a treeview?
Here is the code I have so far:
<script type='text/template' id='listtree_bs'>
<div class="listtree">
<ul>
<% _.each(context, function(element, index){ %>
<li>
<span>
<input class="checkbox-listview-master" type="checkbox" value="<%= element.value %>"><%= element.name %><i class="glyphicon glyphicon-chevron-up"></i>
</span>
<ul style="display: none;">
<% _.each(element.items, function(childelement, index){ %>
<li>
<span>
<input class="checkbox-listview-master" type="checkbox" value="<%= childelement.value %>"><%= childelement.name %><i class="glyphicon glyphicon-chevron-up"></i>
</span>
</li>
<% }); %>
</ul>
</li>
<% }); %>
</ul>
</div>
</script>
var ListTreeModel = Backbone.Model.extend({
urlRoot: "/search/multiselect/",
idAttribute:'value',
});
var ListTreeModels = Backbone.Collection.extend({
model: ListTreeModel,
url: "/search/multiselect/",
parse: function (response) {
return response.data;
}
});
var listtreemodels = new ListTreeModels();
listtreemodels.fetch()
var ListTreeView = Backbone.View.extend({
events: {
"treechecked": "treechecked"
},
treechecked: function( e ){
console.log('triggered');
});
var listtreeview = new ListTreeView({el: $('#listtree_bs')});
The response.data from above looks kind of like this (I can easily change the backend though to facilitate the front end)
{
"data": [
{
"other": 0,
"values": [
{
"value": 1,
"key": "type (35513)"
}
],
"value": "type_of_code",
"key": "C Type",
"missing": 275793
},
{
"other": 25273,
"values": [
{
"value": 41,
"key": "United States of America (187293)"
}
],
"value": "primary_country_id",
"key": "Primary Country",
"missing": 3475
},
{
"other": 10958,
"values": [
{
"value": 623,
"key": "company 623 (12602)"
}
],
"value": "controller_id",
"key": "Search by Controller",
"missing": 248288
},
{
"other": 1294,
"values": [
{
"value": 6,
"key": "animal type (247267)"
},
{
"value": 7,
"key": "animal type y (23315)"
}
],
"value": "animal_id",
"key": "Animals",
"missing": 0
},
{
"other": 0,
"values": [
{
"value": 5,
"key": "Inactive (63693)"
},
{
"value": 1,
"key": "Active (825)"
}
],
"value": "current_status_code_table_id",
"key": "Current Status",
"missing": 109101
},
{
"other": 0,
"values": [
{
"value": 0,
"key": "stuff (275058)"
},
{
"value": 1,
"key": "more stuff (39860)"
},
{
"value": 2,
"key": "even more stuff (668)"
}
],
"value": "stuff_indicator",
"key": "Stuff Indicator",
"missing": 0
}
]
}
so right now, models are populated at the data level, but should they be populated at the nested level and manage this with some kind of one to many relationship?
What these multiselects do is fill out a search form that will get sent back to the server when the user hits search. Can I bind the above views to the model even if they are nested?
I'm trying backbone as an experiment here, but is this what it was really designed for? The search results are complicated and are sliced down in dozens of views. I was hoping to use backbone to keep the dom light and nimble. Right now it's getting bogged down in a lot of event call backs and just a lot of html.
Setting up a hierarchy of models is not that difficult : you just have to build your submodels when you parse the data. One way to do it is
var ListTreeModel = Backbone.Model.extend({
urlRoot: "/search/multiselect/",
idAttribute:'value',
constructor: function(data, opts) {
// force the parsing of the data
opts = _.extend({}, opts, {parse: true});
// setup the children collection
this.values = new ListTreeModels();
// call the parent constructor
Backbone.Model.call(this, data, opts);
},
parse: function(data) {
// populate the children
if (_.isArray(data.values))
this.values.set(data.values);
// remove the children from th emodel attributes
return _.omit(data, 'values');
}
});
var ListTreeModels = Backbone.Collection.extend({
model: ListTreeModel,
url: "/search/multiselect/",
parse: function (response) {
return response.data;
}
});
A demo showing the result http://jsfiddle.net/nikoshr/pZU5J/
Once your model structure is up and running, you can render your views (generate the associated HTML) and defined events. Here is a sample way to do it:
var ListTreeView = Backbone.View.extend({
'tagName': 'ul',
render: function () {
var $el = this.$el;
//create a view for each model
this.collection.each(function(model) {
var view = new ListItemView({
model: model
});
$el.append(view.render().el);
});
return this;
}
});
var ListItemView = Backbone.View.extend({
'tagName': 'li',
events: {
'click ': function(e) {
e.stopPropagation(); // avoid triggering an event on the parent level
console.log(this.model.get('value'));
}
},
render: function () {
//render the node
var template = _.template($('#listitem').html());
this.$el.html(template(this.model.toJSON()));
//and add a view for the sub collection
var subview = new ListTreeView({
collection: this.model.values
});
this.$el.append(subview.render().el);
return this;
}
});
with the listitem template defined as
<script type='text/template' id='listitem'>
<span>
<input class="checkbox-listview" type="checkbox" value="<%= value %>"> <%= key %>
</span>
</script>
And a demo http://jsfiddle.net/nikoshr/pZU5J/3/
Hierarchical views can be tricky to render, you probably will have to investigate further on the matter.

Resources