AngularJS Displaying a sorted $http response in template partial - angularjs

I'm currently working on a project that I need to sort the response by category and subcategory using Angular.
My controller currently looks like:
function($http, $stateParams) {
let vm = this;
$http({
method: 'GET',
url: url,
timeout: 10000,
contentType: "application/json;odata=verbose",
headers: {"Accept": "application/json;odata=verbose"},
params: {},
}).then(function(data, status, headers, config) {
let documents = data.data.d.results;
$.each(documents, function(i, item){
vm.data = sortDocuments(documents);
})
}).catch(function(error) {
console.log(error);
});
function sortDocuments(documents) {
return _.sortBy(documents, item => {
return {
category: item.Category,
subcategory: item.Subcategory,
documentURL: item.EncodedAbsUrl,
tags: item.Tags
}
})
};
})
I need to sort the category and subcategories in my view, but not sure how to go about doing it. My template partial currently looks like:
<div uib-accordion-group class="panel-default" heading="Subcategory Name">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Tags</th>
<th>Link</th>
</tr>
</thead>
<tbody ng-show="item.subcategory == 'Subcategory Name'" ng-repeat="item in documents.data">
<tr>
<td>
<p>{{ item.name }}</p>
</td>
<td>
<p>{{ item.tags.results }}</p>
</td>
<td>
<a href="{{ item.documentURL }}">Open
Document</a>
</td>
</tr>
</tbody>
</table>
</div>
Can anyone tell me what I'm missing in order to sort the view by category and subcategory?

I'm not sure why you're using _.map there. _.sortBy should do what you need.
http://underscorejs.org/#sortBy
this should be pretty close:
vm.data = _.sortBy(data.data.d.results, document => { return document.Category + document.Subcategory } )

Related

Using AngularJS, how can I match items from two separate ng-repeats?

Using AngularJS, I am creating a table that is pulling data with two web requests.
Each web request has it's own ng-repeat in the HTML, ng-repeat="user in users" and ng-repeat="app in apps". Right now all existing apps are showing in every repeat of user. What I'd like to do is some kind of match, lookup, or filter and only show apps that the user is associated with. So, when user.Title == app.Title.
Here is the HTML:
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<div class="ProfileSheet" ng-repeat="user in users">
<h3 class="heading">User Profile</h3>
<table id="Profile">
<tr>
<th>User</th>
<td>{{user.Title}}</td>
</tr>
<tr>
<th>First Name</th>
<td>{{user.FirstName}}</td>
</tr>
<tr>
<th>Last Name</th>
<td>{{user.LastName}}</td>
</tr>
<tr>
<th>Job Title</th>
<td>{{user.JobTitle}}</td>
</tr>
<tr>
<th>Emp ID</th>
<td>{{user.EmployeeID}}</td>
</tr>
<tr>
<th>Officer Code</th>
<td>{{user.OfficerCode}}</td>
</tr>
<tr>
<th>Email</th>
<td>{{user.Email}}</td>
</tr>
<tr>
<th>Telephone</th>
<td>{{user.WorkPhone}}</td>
</tr>
<tr>
<th>Fax Number</th>
<td>{{user.WorkFax}}</td>
</tr>
<tr>
<th>Location Description</th>
<td>{{user.LocationDescription}}</td>
</tr>
<tr>
<th>Mailstop / Banking Center #</th>
<td>{{user.Mailstop}}</td>
</tr>
</table>
<br>
<h3 class="heading">User Applications</h3>
<div style="border:3px solid #707070; padding-right:12px;">
<h4 style="padding-left:5px;">User Applications</h4>
<table id="Apps">
<tr id="AppsHeading">
<th>Application</th>
<th>User ID</th>
<th>Initial Password</th>
<th>Options / Comment</th>
<th>Setup Status</th>
</tr>
<tr ng-repeat="app in apps">
<td>{{app.Application.Title}}</td>
<td>{{app.Title}}</td>
<td>{{app.InitialPassword}}</td>
<td>{{app.OptionsComments}}</td>
<td style="border-right:3px solid #707070;">{{app.SetupStatus}}</td>
</tr>
</table>
</div>
</div>
</div>
The JS:
var app = angular.module('myApp', ['ngSanitize']);
var basePath = "https://portal.oldnational.com/corporate/projecthub/anchormn/associates"
app.controller('MainCtrl', function($scope, $http, $q){
var supportList;
$(document).ready(function() {
$scope.getAdminList();
$scope.getAppsList();
});
// $scope.selectedIdx = -1;
// $scope.showResults = false
$scope.prepContext = function(url,listname,query){
var path = url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query;
console.log(path);
return path;
}
$scope.getAdminList = function() {
supportList = $http({
method: 'GET',
url: this.prepContext(siteOrigin+"/corporate/projecthub/anchormn/associates","User Administration","?$orderBy=LastName"),
headers: {
"Accept": "application/json; odata=verbose"
}
}).then(function(data) {
//$("#articleSection").fadeIn(2000);
console.log("adminlist", data.data.d.results);
$scope.users = data.data.d.results;
});
};
$scope.getAppsList = function() {
supportList = $http({
method: 'GET',
// url: this.prepContext(siteOrigin+"/corporate/projecthub/anchormn/associates","User Applications","?$select=Title,InitialPassword,OptionsComments,SetupStatus,Application/Title&$orderBy=Application&$expand=Application"),
url: this.prepContext(siteOrigin+"/corporate/projecthub/anchormn/associates","User Applications","?$select=Title,InitialPassword,OptionsComments,SetupStatus,Application/Title,ParentUserLink/ID&$orderBy=Application&$expand=Application,ParentUserLink"),
headers: {
"Accept": "application/json; odata=verbose"
}
}).then(function(data) {
//$("#articleSection").fadeIn(2000);
console.log("appslist", data.data.d.results);
$scope.apps = data.data.d.results;
});
};
});
app.config([
'$compileProvider',
function($compileProvider){
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrom-extension|javascript):/)
}
]);
How can I do this?
There's a lot of extraneous code in the controller. For the purposes of this answer I removed it. Also I understand that users and apps are related by a property called Title but the name was confusing me - forgive me if the data doesn't make sense.
Suggestion: Only use $(jQuery) where strictly necessary. Angular provides a lot of functionality that replaces jQuery functionality. Instead of using $.ready like:
$(document).ready(function() {
$scope.getAdminList();
$scope.getAppsList();
});
wait to bootstrap your application until the document is ready using the following code:
(function () {
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
})();
Then you don't have to burden the controller with the responsibility of waiting until the document is loaded. Note: ng-app was removed from the markup.
Suggestion: Use $q.all() to wait for multiple promises to resolve. $q.all() will wait until all promises resolve to call .then(). This helps to ensure that all data is available when you start to use it.
Suggestion: Only assign properties and functions to $scope if they will be used by the view. I removed the functions that are not used by the view from the $scope object.
How does it work?
When the controller loads, we use $q.all() to invoke and wait for fetchAdminList() and fetchAppsList() to fetch data from an API. Once each API request resolves we unwrap the data in .then() callbacks and return it (read more on promise chaining to understand what happens when a value is returned from .then()). When both promises resolve, we store the data on $scope to make it available to the view. We also pre-compute which applications each user can use and store that data in $scope.userApps to make it available to the view.
I did not have access to the APIs you are fetching data from. I substituted $http calls with an immediately resolving promise using $q.resolve() and static data. When you are ready just replace $q.resolve(...) with the original $http(...) calls in the fetch functions.
Run the snippet to see it in action.
var app = angular.module('myApp', []);
(function () {
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
})();
var USERS = [
{
Title: 'Software Engineer',
FirstName: 'C',
LastName: 'Foster',
EmployeeID: 1
},
{
Title: 'Software Engineer',
FirstName: 'J',
LastName: 'Hawkins',
EmployeeID: 2
},
{
Title: 'CEO',
FirstName: 'Somebody',
LastName: 'Else',
EmployeeID: 3
}
];
var APPS = [
{
Application: { Title: 'StackOverflow' },
Title: 'Software Engineer'
},
{
Application: { Title: 'Chrome' },
Title: 'Software Engineer'
},
{
Application: { Title: 'QuickBooks' },
Title: 'CEO'
}
]
app.controller('MainCtrl', function ($scope, $http, $q) {
$q.all({
users: fetchAdminList(),
apps: fetchAppsList()
})
.then(function(result) {
// Store results on $scope
$scope.users = result.users;
$scope.apps = result.apps;
// Pre-compute user apps
$scope.userApps = $scope.users.reduce(
function(userApps, user) {
userApps[user.EmployeeID] = getUserApps(user.Title);
return userApps;
},
[]
);
});
function fetchAdminList() {
return $q.resolve({ data: { d: { results: USERS } } })
.then(function (data) { return data.data.d.results; });
}
function fetchAppsList() {
return $q.resolve({ data: { d: { results: APPS } } })
.then(function (data) { return data.data.d.results; });
}
// Get a list of apps that apply to user title
function getUserApps(userTitle) {
return $scope.apps.filter(function(app) {
return app.Title === userTitle;
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<div>
<div ng-controller="MainCtrl">
<div class="ProfileSheet" ng-repeat="user in users">
<h3 class="heading">User Profile</h3>
<table id="Profile">
<tr>
<th>User</th>
<td>{{user.Title}}</td>
</tr>
<tr>
<th>First Name</th>
<td>{{user.FirstName}}</td>
</tr>
<tr>
<th>Last Name</th>
<td>{{user.LastName}}</td>
</tr>
<tr>
<th>Job Title</th>
<td>{{user.JobTitle}}</td>
</tr>
<tr>
<th>Emp ID</th>
<td>{{user.EmployeeID}}</td>
</tr>
<tr>
<th>Officer Code</th>
<td>{{user.OfficerCode}}</td>
</tr>
<tr>
<th>Email</th>
<td>{{user.Email}}</td>
</tr>
<tr>
<th>Telephone</th>
<td>{{user.WorkPhone}}</td>
</tr>
<tr>
<th>Fax Number</th>
<td>{{user.WorkFax}}</td>
</tr>
<tr>
<th>Location Description</th>
<td>{{user.LocationDescription}}</td>
</tr>
<tr>
<th>Mailstop / Banking Center #</th>
<td>{{user.Mailstop}}</td>
</tr>
</table>
<br>
<h3 class="heading">User Applications</h3>
<div style="border:3px solid #707070; padding-right:12px;">
<h4 style="padding-left:5px;">User Applications</h4>
<table id="Apps">
<tr id="AppsHeading">
<th>Application</th>
<th>User ID</th>
<th>Initial Password</th>
<th>Options / Comment</th>
<th>Setup Status</th>
</tr>
<tr ng-repeat="app in userApps[user.EmployeeID]">
<td>{{app.Application.Title}}</td>
<td>{{app.Title}}</td>
<td>{{app.InitialPassword}}</td>
<td>{{app.OptionsComments}}</td>
<td style="border-right:3px solid #707070;">{{app.SetupStatus}}</td>
</tr>
</table>
</div>
</div>
</div>

Selecting default value using ngModel ngRepeat, ngOptions

Hopefully someone can help.
I am developing an application using HTML AngularJs which uses ng-repeat,ng-options and ng-model and populates multiple rows based on the data in the database for a user. Each row has static data coming from DB (returned as object via restAPI) and dynamic select option for user selection. Select option is hardcoded in app.js and linked to model on HTML for DB update upon selection using update button. Each row has its own button and i can see update function is working at row level.
I want to set the default value of the drop down list dynamically as value of an element coming from database. Object is same as one being used to populate rows with static data .
Code is in the fiddle at https://jsfiddle.net/6j88L61y/4/
HTML below
<body>
<h1 align="center">User Tracker</h1>
<div ng-controller="MainController as main">
<div>
<p>Please Enter ID </p>
<p>
<input type="text" ng-model="main.model.userName"></input>
<button ng-click="main.model.getOrgList()">List State List</button>
</p>
</div>
<hr ng-show="main.model.formSubmitted"></hr>
<div>
<table class="table table-bordered" border="1">
<thead>
<tr>
<th>ID</th>
<th>User Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="org in main.model.orgList" id="{{org.id}}">
<td>{{org.id}}</td>
<td align="center">{{org.user}}</td>
<td align="center">
<select ng-model="main.model.selectedRecord.appCurrentStateSelected[$index]" ng-options="option.value as option.value for option in main.model.appCurrentStateList" ></select>
</td>
<td>
<button ng-click="main.model.updateAppDetailsList({id:org.id,userName:org.name,appCrntState:main.model.selectedRecord.appCurrentStateSelected})">Update</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
JS
"use strict";
angular.module('myApp',[]);
angular.module('myApp').service('AppModel', function( $http) {
this.userId='';
this.userName ="";
this.formSubmitted="";
this. selectedRecord ={appCurrentStateSelected:''};
this.appCurrentStateList =[{name: 'New',value:'New',id:1}, {name: 'InUse',value:'InUse',id:2},{name: 'Inactive',value:'Inactive',id:3},{name: 'Deleted',value:'Deleted',id:4}];
this.submittedAppDetailsList=[];
console.log(' json sample:'+this.submittedAppDetailsList);
var path = 'home';
var currentProtocol = location.protocol;
var host =location.host;
var apiHost = currentProtocol+'//'+host+'/api/';
console.log('API url is : ' +apiHost);
// Get method
this.getOrgList = function() {
var path = 'home/userid';
console.log(this.userName);
console.log(this.selectedRecord);
$http.get(apiHost+path+'/'+this.userName+'/')
.then(function(response) {
this.orgList =response.data;
this.formSubmitted = true;
console.log(response.data);
}.bind(this),
function(response) {
console.log(response.data);
});
}
// Post method
this.updateAppDetailsList = function(appdetailsList) {
var path = 'home/update';
console.log(this.selectedRecord);
$http.post(apiHost+'home/update/',appdetailsList)
.then(function(response) {
this.submittedAppDetailsList.push(response.data);
this.formSubmitted = false;
console.log(response.data);
}.bind(this),
function(response) {
console.log('Error : '+response.data);
});
}
});
angular.module('myApp').controller('MainController', ['AppModel', function (AppModel) {
this.model = AppModel;
}]);

Angular in electron, slow rendering for large json

I'm currently learning Electron and using AngularJS.
I've my REST api in node and express and my database is MongoDB.
this is my route
router.get('/branch/:branch',function (req,res,next) {
var br = req.params.branch;
var final = [];
db.collection('users').find({"branch": br}, function (err, docs) {
docs.forEach(function (ele) {
console.log(ele['fir_id']);
final.push(ele['fir_id']);
})
db.punch_coll.find(function (err, docs) {
var d = [];
console.log(final);
docs.forEach(function (ele) {
console.log(ele['fir_id']);
if(final.includes(parseInt(ele['fir_id']))) {
ele['date'] = ele['date'].toDateString();
ele['punch_in'] = ele['punch_in'].substring(0, 8);
ele['punch_out'] = ele['punch_out'].substring(0, 8);
d.push(ele);
}
console.log(d);
})
console.log(d);
res.send(d);
})
});
});
punch_coll document
{
_id: 58e21075e0c6800ce8b08d92,
fir_id: '4',
date: 'Mon Apr 03 2017',
punch_in: '14:35:57',
punch_out: ''
}
user document
{
_id: 58e20ee0e0c6800ce8b08d82,
name: 'A B C',
fir_id: 1,
branch: 'CSE',
year: 'SE'
}
HTML and Angular Controller Script
<body ng-app="myApp" ng-controller="myCtrl">
<form class="pure-form">
<strong>Enter FIR-ID</strong> <input type="text" ng-model="fid" ng-
change="change()" class="pure-input-rounded">
</form>
</br>
<div class="pure-g">
<div class="pure-u-8-24" style="border-style: solid;border-
color:lightgrey;">
<header class="w3-container w3-light-grey">
<h2>Fir ID :- {{fid}}</h2>
<h3>Name :- {{user[0].name}} </h3>
</header>
<div class="w3-container">
<h2>Branch :- {{user[0].branch}} </h2>
<hr>
<h2>Academic Year :- {{user[0].year}} </h2>
</div>
</div>
</div>
<form class="pure-form">
<select id="state" ng-model="branch" ng-change="changeBranch()">
<option>CSE</option>
<option>MECH</option>
<option>CIVIL</option>
<option>ENTC</option>
</select>
</form>
<!-- <h2>Fir ID :- {{fid}}</h2>
<h2>Name :- {{user[0].name}} </h2>
<h2>Branch :- {{user[0].branch}} </h2>
<h2>Academic Year :- {{user[0].year}} </h2> -->
<div style="right:0;top:0;position:absolute;font-size:20px;">
<table class="pure-table pure-table-horizontal">
<thead>
<tr>
<th>Fir ID</th>
<th>Date</th>
<th>Punch In</th>
<th>Punch Out</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in name">
<td>{{ x.fir_id }}</td>
<td>{{ x.date }}</td>
<td>{{ x.punch_in }}</td>
<td>{{ x.punch_out }}</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
// You can also require other files to run in this process
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.name;
$scope.user;
$scope.fid;
$scope.branch='CSE';
$scope.change = function() {
//get punches for specific fir_id
$http.get('http://localhost:3000/users/'+$scope.fid)
.then(function(response) {
$scope.user=response.data;
})
//get punches for specific fir_id
$http.get('http://localhost:3000/punch/'+$scope.fid)
.then(function(response) {
console.log(response.status);
$scope.name=response.data;
}, function errorCallback(response) {
$scope.name=null;
});
};
$scope.changeBranch = function(){
//get record as per branch
$http.get('http://localhost:3000/branch/'+$scope.branch)
.then(function(response) {
console.log(response.status);
$scope.name=response.data;
}, function errorCallback(response) {
$scope.name=null;
});
};
});
The table is rendering slow for large json takes 1second it's like it's lagging.
I'm new to this so of course I'm doing something horrible. I think the way I'm using that async functions are bad also but dont know whats making it slow foreach or anything else.
So, after replacing foreach with simple for loop it solved the problem but I don't know whats the exact reason. Anyone had same problem?

how to pass the JSON data from the controller to AngularJS in asp.net mvc?

i want to pass the json data from controller to angularjs..i have tried the below code but just only show the table header don't show my product data..below put my code..
this is my angularjs code..
$scope.ViewPro = function () {
$http({ method: 'GET', url: 'AddToCart/ProList' }).
success(function (p) {
debugger;
console.log(p);
$scope.Products = p; // Response Data
$location.path('/ViewProduct');
}).
error(function (data) {
alert(data + "Error");
console.log(data);
});
};
this is my json controller method..
public JsonResult ProList()
{
var ProductList = db.tblProducts.ToList();
var Products = ProductList.Select(d => new
{
d.ProductId,
d.ProductName,
d.Price,
d.Descripation,
d.SEOURL,
d.Image,
d.IsPubliesd,
}).ToList();
return Json(Products, JsonRequestBehavior.AllowGet);
}
this is my routeProvider
.when('/ViewProduct', { templateUrl: 'AddToCart/ViewProduct' })
this is my view..
#model IEnumerable<AJSWithShoppingCart.Models.tblProduct>
<div ng-app="MyApp" ng-controller="AddToCart" ng-model="AddToCart">
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<td align="center"><b>ProductId</b></td>
<td align="center"><b>ProductName</b></td>
<td align="center"><b>Descripation</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>SEOURL</b></td>
<td align="center"><b>IsPubliesd</b></td>
<td align="center"><b>AddToCart</b></td>
</tr>
<tr ng-repeat="Product in Products">
<td ng-bind="Product.ProductId"></td>
<td>{{Product.ProductName}}</td>
<td>{{Product.Descripation}}</td>
<td>${{Product.Price}}.00</td>
<td>{{Product.SEOURL}}</td>
<td>{{product.ispubliesd}}</td>
</tr>
</table>
</div>
</div>

two json files and a function into controller and a view

I'm relatively new to Angular and got stuck with something ....
I'm trying to add a function to my controller and then to my view/html that would allow me mark a Vote <button> active/inactive based on the result of comparison of data from two different json files. Pseudo code would be something like this
if Vote exists:
display disabled vote button with a number of existing votes
else:
display active vote button (with a number of existing votes) and then disable it after vote has been submitted
that function would be checking if link.id list exists in users's vote.link/id list
link json example
{"description": "Lorem Ipsum", "id": 1, "resource_uri": "/api/v1/links/1/", "timestamp_added": "2015-02-15T17:22:33.300349", "url": "http://google.com/", "user": "user1"}
vote json example
{"id": 351, "resource_uri": "/api/v1/votes/351/", "timestamp_added": "2015-03-30T15:00:09.622308", "user": "user1", "vote": "up", "voted_link": "1"}
controller.js
app.controller('LinksCtrl', function ($scope, $http){
$http.get('http://localhost:8001/api/v1/links/?limit=0').
success(function(data) {
console.log('http.get OK');
$scope.links = data;
});
$http.get('http://localhost:8001/api/v1/votes/?limit=0').
success(function(data) {
console.log('http.get OK');
$scope.votes = data;
});
$scope.sortField = 'objects.likes';
$scope.reverse = true;
<!-- ############# LOOKING FOR HELP WITH THIS FUNCTION ###########
$scope.isDisabled = function (link_id) {
return "true if link_id is present in the list of link IDs from the votes array" );
};
-->
$scope.voteUp = function(id){
$http.post('http://localhost:8001/api/v1/votes/', {
user: "user1",
voted_link: "1",
vote: "up"
}).
success(function(data, status, headers, config) {
console.log('http.post OK');
}).
error(function(data, status, headers, config) {
console.log('http.post NOK');
});
};
});
view.html
<div ng-controller="LinksCtrl">
<tr ng-repeat="link in links.objects">
<td>{{ link.url }}</td>
<td>{{ link.description }}</td>
<td><button
ng-disabled="isDisabled(link.id)"
ng-click="voteUp(link.id)"
>Vote
</button></td>
</tr>
</div>
Code also here: https://jsfiddle.net/v6hkz9rr/7/.
Any ideas how should I be going about it?
thanks
-s
I modified your example to match your request. check this out
i replaced $http calls with static data for the demo
js
var app = angular.module('plunker', []);
app.controller('LinksCtrl', function($scope) {
$scope.links = {
objects: [{
id: 1,
url: 'https://facebook.com',
description: 'facebook the social network',
votes: 4
}, {
id: 2,
url: 'https://google.com',
description: 'google inc',
votes: 10
}]
};
$scope.votes = [];
/*-- ############# LOOKING FOR HELP WITH THIS FUNCTION ########### */
$scope.isDisabled = function(link) {
return $scope.votes.indexOf(link.id) >= 0;
};
$scope.voteUp = function(link) {
link.votes++;
$scope.votes.push(link.id);
}
});
html
<body ng-controller="LinksCtrl">
<div class="container">
<h4>Links</h4>
<table class="table table-bordered">
<thead>
<tr>
<th>
url
</th>
<th>
description
</th>
<th>
#
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="link in links.objects">
<td>{{ link.url }}</td>
<td>{{ link.description }}</td>
<td>
<button class="btn btn-xs btn-default" ng-disabled="isDisabled(link)" ng-click="voteUp(link)">Vote ({{link.votes}})</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
http://plnkr.co/edit/xPEnB4inzZxVUBsWpaw1?p=preview

Resources