dropdown values load sometimes and sometimes not in angularjs - angularjs

I am working on angularjs , where I am loading dropdowns from database in angularjs controller. I am facing an intermittent issue that sometimes dropdown values load and sometimes don't . Its working on my local but when I upload on server this intermittent issue is coming.
I have even tried to use ng-init on html and then put login there in that function but still this issue is there.
here is html
<div class="x_panel" ng-init="loadDropDownData()">
<div class="x_title">
<h2 id="EditjobTitle" style="display:none">Edit Job<small></small></h2>
<button class="btn col-md-offset-9" id="btnBack" style="display:none" ng-click="Cancel()">Back</button>
<h2 id="NewjobTitle">New Engagement<small></small></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br>
<form name="JobForm" id="demo-form2" data-parsley-validate="" class="form-horizontal form-label-left" novalidate="">
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3 save-buttons">
<button type="submit" class="btn btn-success" ng-click="JobForm.$valid && save()">Save</button>
<button class="btn" ng-click="Cancel()">Cancel</button>
</div>
</div>
<h5>Job Data</h5>
<input type="hidden" id="JobID" ng_value="{{Job.JobNum}}">
<div class="form-group">
#Html.Label("Job Name", new { #class = "control-label control-label-j col-md-2 col-sm-3 col-xs-12" })
<div class="col-md-3 col-sm-3 col-xs-12">
<input type="text" name="JobName" ng-model="Job.JobName" ng-minlength="4" id="txtJobName" class="form-control col-md-7 col-xs-12" required="" maxlength=25>
</div>
#Html.Label("EngType", new { #class = "control-label control-label-j col-md-2 col-sm-3 col-xs-12" })
<div class="col-md-3 col-sm-3 col-xs-12">
<select name="EngType" ng-model="Job.EngType" ng-options="s.ID as s.EngTypes for s in Job.lstEngType" class="form-control col-md-7 col-xs-12" required="">
<option value="">-- Select EngType --</option>
</select>
</div>
</div>
</form>
</div>
</div>
and Js file is as below
app.controller('AddJobController', function ($scope, $location, $filter, ShareData, jobService, $compile) {
$scope.phoneNumbr = /^\+?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
$scope.datePattern = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/i
$scope.regEx = "/^[0-9]{10,10}$/;";
$scope.listOfStatus = [];
$scope.showStatusError = false;
$scope.statusText = "";
$scope.loadDropDownData = function() {
loadJobInitdata();
}
$(document).ready(function () {
$("#txtCloseDate").datepicker({ format: 'mm/dd/yyyy' });
$("#txtDraft_Date").datepicker({ format: 'mm/dd/yyyy' });
$("#txtFinal_Date").datepicker({ format: 'mm/dd/yyyy' });
$("#txtOpenDate").datepicker({ format: 'mm/dd/yyyy' });
$("#txtFinalSent").datepicker({ format: 'mm/dd/yyyy' });
$('body').off('click', '.remove-record').on('click', '.remove-record', function () {
removeSpan = "";
var addButton = "<div class='col-md-3 col-sm-3 col-xs-12'>\
<input type='button' class='btn btnAddDeadline' value='Add Deadline' />\
</div>";
var ifAdd = false;
if ($(this).parent().find('.btnAddDeadline').length == 1) {
ifAdd = true;
}
if ($scope.Job.JobNum != null && $scope.Job.JobNum != undefined) {
var ID = $(this).parent().find('.deadline-datepicker').attr('id')
ID = ID.replace("Date", "");
var removeSpanElement = $(this);
if (ID != "txtDeadlines") {
var promiseDeleteDeadline = jobService.DeleteDeadline(ID)
promiseDeleteDeadline.then(function () {
removeSpanElement.parent().remove();
if (ifAdd) {
PopulateDeadline(null, addButton, removeSpan);
$('.deadline-datepicker').datepicker({
ignoreReadonly: true,
startDate: new Date()
});
}
})
}
else {
$(this).parent().remove();
if (ifAdd) {
PopulateDeadline(null, addButton, removeSpan);
$('.deadline-datepicker').datepicker({
ignoreReadonly: true,
startDate: new Date()
});
}
}
}
else {
$(this).parent().remove();
if (ifAdd) {
PopulateDeadline(null, addButton, removeSpan);
$('.deadline-datepicker').datepicker({
ignoreReadonly: true,
startDate: new Date()
});
}
}
});
})
if (ShareData.value == 0) {
//loadJobInitdata();
}
else {
Edit();
}
$scope.maxlength = 3;
$scope.Job = [];
function Edit() {
if (!ShareData.createAsNewJob) {
$('#NewjobTitle').hide();
$('#EditjobTitle').show();
$('#btnBack').show();
}
//loadJobInitdata();
var promiseEditjobData = jobService.EditJob(ShareData.value);
promiseEditjobData.then(function (jobdata) {
GetDeadlinesbyJobID(ShareData.value);
getStatusCommentsJobId(ShareData.value);
$scope.Job = jobdata.data;
var CloseDate = $scope.Job.CloseDate = (jobdata.data.CloseDate != null && jobdata.data.CloseDate != undefined) ? $filter('date')(new Date(jobdata.data.CloseDate), 'MM/dd/yyyy') : null
var OpenDate = $scope.Job.OpenDate = jobdata.data.OpenDate = (jobdata.data.OpenDate != null && jobdata.data.OpenDate != undefined) ? $filter('date')(new Date(jobdata.data.OpenDate), 'MM/dd/yyyy') : null
var Draft_Date = $scope.Job.Draft_Date = jobdata.data.Draft_Date = (jobdata.data.Draft_Date != null && jobdata.data.Draft_Date != undefined) ? $filter('date')(new Date(jobdata.data.Draft_Date), 'MM/dd/yyyy') : null
var Final_Date = $scope.Job.Final_Date = jobdata.data.Final_Date = (jobdata.data.Final_Date != null && jobdata.data.Final_Date != undefined) ? $filter('date')(new Date(jobdata.data.Final_Date), 'MM/dd/yyyy') : null
$scope.Job.Deadlines = jobdata.data.Deadlines = (jobdata.data.Deadlines != null && jobdata.data.Deadlines != undefined) ? $filter('date')(new Date(jobdata.data.Deadlines), 'MM/dd/yyyy') : null
console.log(new Date(CloseDate));
var myDate = new Date(1978, 2, 11)
if (CloseDate != null) { $("#txtCloseDate").datepicker("update", new Date(CloseDate)); }
if (OpenDate != null) { $("#txtOpenDate").datepicker("update", new Date(OpenDate)); }
if (Draft_Date != null) { $("#txtDraft_Date").datepicker("update", new Date(Draft_Date)); }
if (Final_Date != null) { $("#txtFinal_Date").datepicker("update", new Date(Final_Date)); }
ShareData.value = 0;
if (ShareData.createAsNewJob == true) {
$scope.Job.JobNum = null;
ShareData.createAsNewJob = false;
}
},
function (errorPl) {
$scope.error = errorPl;
ShareData.value = 0;
alert($scope.error);
});
}
function loadJobInitdata() {
var promiseLoadDLLs = jobService.GetJobInitData();
promiseLoadDLLs.then(function (pl) {
//$scope.Job = pl.data
$scope.Job.lstEngType = pl.data.lstEngType,
$scope.Job.lstWorkProduct = pl.data.lstWorkProduct,
$scope.Job.lstNAICSCode = pl.data.lstNAICSCode,
$scope.Job.lstSubject = pl.data.lstSubject,
$scope.Job.lstManager = pl.data.lstManager,
$scope.Job.lstClientType = pl.data.lstClientType,
$scope.Job.lstFeeBasis = pl.data.lstFeeBasis,
$scope.Job.lstBillingCycle = pl.data.lstBillingCycle,
$scope.Job.lstExpenses = pl.data.lstExpenses,
$scope.Job.lstSalesperson = pl.data.lstSalesperson,
$scope.Job.lstPriority = pl.data.lstPriority,
$scope.Job.lstStaff = pl.data.lstStaff,
$scope.Job.lstLogo_in_Client_Logo_File = pl.data.lstLogo_in_Client_Logo_File,
$scope.Job.lstTombstone_Status = pl.data.lstTombstone_Status
},
function (errorPl) {
$scope.error = errorPl;
alert($scope.error);
});
}
$scope.Cancel = function () {
$location.path(ShareData.page);
}
$scope.AddDeadline = AddDeadline;
});

Related

How to manipulate ngfor table, to toggle between two arrays

I would like to know if there is a simple way of parsing different array to a single *ngfor table. I have the below codes:
.html
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="date" (click)="valid()" />
<label class="form-check-label">Valid</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="date" (click)="invalid()"/>
<label class="form-check-label">Invalid</label>
</div>
</div>
<tr *ngFor="let myAccount of Account | filterBy: accountFilter | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
<td>{{ (p - 1) * count + i + 1 }}</td>
<td>{{myAccount.name}}</td>
<td>{{myAccount.startDate}}</td>
<td>{{myAccount.endDate}}</td>
</tr>
.ts
Account = [];
radioAccount = [];
currentDate = '';
ngOnInit() {
showAll();
}
showAll() {
return this.acctService.getAccount().subscribe(data => this.Account = data);
}
valid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.radioAccount = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate > this.currentDate});
}
invalid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.radioAccount = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate <= this.currentDate});
}
You can see that I have two arrays, how do I display content of "radioAccount" array when a radio button is clicked? That is, the possibility of swiching between "Account" content and "radioAccount" content. I don't think repeating the *ngfor code with *ngif is a solution.
You can create an array which will not be filtered, e.g., AccountSource and then you can assign original values (AccountSource) to Account:
Account = [];
AccountSource= [];
showAll() {
return this.acctService.getAccount()
.subscribe(data => {
this.Account = data;
this.AccountSource = data;
});
}
valid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.Account = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate > this.currentDate});
}
invalid() {
this.currentDate = this.datePipe.transform(new Date(),"yyyy-MM-dd");
this.Account = this.Account.filter(data => {
return data.startDate < this.currentDate && data.endDate <= this.currentDate});
}
setSourceData() {
this.Account = this.AccountSource;
}
and call setSourceData() method whenever you want to see original values.

React-share. Throws error TypeError: Super expression must either be null or a function, not undefined when trying to use it in require

I am new in ReactJs and trying to learn it. I installed a package of react-share. Since i am trying to edit someone else's code i am not able to import the package due to webpack I believe. Every time i try to import a package I receive an error saying the import should always be on top of the script. I tried using require and I get this error in Console
TypeError: Super expression must either be null or a function, not undefined
My code looks like this:
"use strict";
require('./../../../assets/styles/components/thread.less');
var reactShare = require('react-share');
var React = require('react');
var ReactDOM = require('react-dom');
var Fluxxor = require('fluxxor');
var _ = require("lodash");
var FluxMixin = Fluxxor.FluxMixin(React);
var StoreWatchMixin = Fluxxor.StoreWatchMixin;
var routerShape = require('react-router').routerShape;
var MicroAudioViews = require('./../../constants/MicroAudioViews');
var AudioModes = require("./../../constants/AudioModes");
var i18n = require("i18next-client");
//components
var AudioVisualizer = require('../elements/AudioVisualizer');
var ReviewOverlay = require('../elements/ReviewOverlay');
var ReviewShare = require('../elements/ReviewShare');
var Menu = require('../elements/Menu');
I have to use react-share's
<FacebookShareButton url={shareLink} quote={title} className="social-media-icon">
<FacebookIcon size={32} round />
</FacebookShareButton>`
Component to share the shareLink on facebook.
Here the full code.
/*import {
FacebookShareButton,
GooglePlusShareButton,
TwitterShareButton,
WhatsappShareButton,
FacebookIcon,
TwitterIcon,
WhatsappIcon
} from 'react-share';*/
"use strict";
require('./../../../assets/styles/components/thread.less');
var reactShare = require('react-share');
var React = require('react');
var ReactDOM = require('react-dom');
var Fluxxor = require('fluxxor');
var _ = require("lodash");
var FluxMixin = Fluxxor.FluxMixin(React);
var StoreWatchMixin = Fluxxor.StoreWatchMixin;
var routerShape = require('react-router').routerShape;
var MicroAudioViews = require('./../../constants/MicroAudioViews');
var AudioModes = require("./../../constants/AudioModes");
var i18n = require("i18next-client");
//components
var AudioVisualizer = require('../elements/AudioVisualizer');
var ReviewOverlay = require('../elements/ReviewOverlay');
var ReviewShare = require('../elements/ReviewShare');
var Menu = require('../elements/Menu');
var Review = React.createClass({
mixins:[
FluxMixin,
StoreWatchMixin("ThreadStore", "RecordStore", "ReviewStore", "ApplicationStore", "SyncStore", "DemoStore", "ShareStore")
],
contextTypes: {
router: routerShape.isRequired
},
/* react interface*/
getInitialState: function() {
var selectedThreads = [];
var shareType = 'thread';
if(this.props.location.state && this.props.location.state.type == "thread") {
selectedThreads.push(this.props.location.state.threadId);
} else if(this.props.location.state && this.props.location.state.type == "share") {
shareType = 'facebook';
} else if (this.props.location.state && this.props.location.state.type == 'sharereply') {
shareType = 'sharereply';
}
return {
threadUserId: this.props.params.id,
activeShareType: shareType,
selectedThreads: selectedThreads
};
},
getStateFromFlux: function() {
var flux = this.getFlux();
var recordStoreState = flux.store('RecordStore').getState();
var threadStoreState = flux.store('ThreadStore').getState();
var appStoreState = flux.store('ApplicationStore').getState();
var reviewStoreState = flux.store('ReviewStore').getState();
var shareStoreState = flux.store('ShareStore').getState();
var demoState = flux.store('DemoStore').getState();
var activeRecord = recordStoreState.activeRecord || null;
var activeThread = threadStoreState.activeThread;
var activeRecordUser = null;
var authenticatedUser = appStoreState.demoMode? demoState.user : appStoreState.user;
var state = {
demoMode: appStoreState.demoMode,
playing: recordStoreState.playing,
recording: recordStoreState.recording,
activeThread: activeThread,
threads: threadStoreState.threads,
authenticatedUser: authenticatedUser,
activeRecord: activeRecord,
activeShareUser: shareStoreState.user,
shareId: shareStoreState.shareId
};
return state;
},
render: function() {
var threadClass = "thread";
var fbClass = "facebook";
var explanationText, usageContent;
var finishButtonClass = 'finish-button';
if(this.state.activeShareType == "thread") {
threadClass += ' active';
explanationText = i18n.t('content:review.reviewDoneExpl', {
count: this.state.selectedThreads.length,
context: this.state.selectedThreads.length == 0 ? 'doselect' : undefined
});
finishButtonClass += this.state.selectedThreads.length == 0 ? ' inactive' : '';
var threadCards = [];
var self = this;
_.each(this.state.threads, function(thread){
var threadUser = thread.user;
var threadUserPicture = threadUser.pictures[0].source;
var userName = threadUser.firstName + ' ' + threadUser.lastName;
var styleProps = {
backgroundImage : threadUserPicture ? 'url(' + threadUserPicture + ')': 'none'
};
var cls = "thread card" + (self.state.selectedThreads.indexOf(thread.id) != -1? " selected" : "");
threadCards.push(<div key={thread.id} className={cls} onClick={self.onThreadCardSelected} data-thread-id={thread.id}>
<div className='pic' style={styleProps}></div>
<div className='name'>{userName}</div>
<div className='checked micro-audio-icon-check'></div>
</div>);
});
//if thread cards array is null then we are displaying the required text
if(threadCards.length==0){
var text= "Du hast noch keine Freunde in audiyoh hinzugefugt (gehe dafur zur Suche).";
//displaying the content
usageContent = (
<div className="usage-target-container">
<p className="chat-text">{text} <br/>Uber <img className="share-icon" src={require('./../../../assets/images/share-active.png')} /> Teilen kannst du deine Aufnahme in aderen Kanale teilen.</p>
</div>);
//displaying the button
var finishContainer = <div className="finish-container">
<div className={finishButtonClass} >Fertige</div>
<div className="finish-text"><p className="chat-underbtn-text">Mindestens <b> ein Gesprach <br/> wahlen,</b> dem die Aufnahme <br/> hinzugefugt werden soll</p></div>
</div>;
}else{
usageContent = (
<div className="usage-target-container">
{threadCards}
</div>);
}
} else {
fbClass += ' active';
finishButtonClass += ' facebook';
explanationText = i18n.t('content:review.facebookExplanation');
//displaying the input box with the link and copy button
console.log("THe shareStoreState is " + this.state.shareId);
//the shareId is generate asynchroneously, so this.state.shareId can be null
if(typeof this.state.shareId === "string") {
//the link can be created like this:
var shareLink = window.location.origin + '/shared/' + this.state.shareId;
}
var usageContent = (
<div className="usage-target-container">
<div className="socialLinkContainer">
<p> Link zum Teilen </p>
<input className="copylink" type="text" value={shareLink} id="shareLink" /><br/>
<input className="copybtn" type="button" onClick={this.copytoclipboard} value="Link kopieren" />
</div>
</div>);
var finishContainer = <div className="finish-container">
<div className="social-media">
/*<img className="social-media-icon" src={require('./../../../assets/images/facebook.png')} />*/
<FacebookShareButton
url={shareLink}
quote={title}
className="social-media-icon">
<FacebookIcon
size={32}
round />
</FacebookShareButton>
<img className="social-media-icon" src={require('./../../../assets/images/whatsapp.png')} />
<img className="social-media-icon" src={require('./../../../assets/images/twitter.png')} />
<img className="social-media-icon" src={require('./../../../assets/images/instagram.png')} />
</div>
</div>;
}
var targetSwitchElements = [
<div title={i18n.t('content:review.sharethread')}
key="thread"
className={threadClass}
onClick={this.activateThreadShareType}><span>audiyoh-chat</span></div>,<br/>,
<div title={i18n.t('content:review.sharefb')}
key="facebook"
className={fbClass}
onClick={this.activateFBShareType}><span>Teilen</span></div>
];
//we either want to save a profile record a share response, so we dont need the fb/thread switch and thread cards
if(this.props.location.state && ["profile", "sharereply"].indexOf(this.props.location.state.type) != -1) {
var buttonText = i18n.t('content:review.profile');
if(this.props.location.state.type == "sharereply"){
buttonText = i18n.t('content:review.share', {name: this.state.activeShareUser.firstName});
}
targetSwitchElements = <div className="profile-record" onClick={this.onFinishRecord}>{buttonText}</div>;
usageContent = null;
finishContainer = null;
}
return (
<div className="ma-reviewing">
<div className="review-controls">
<div className="row">
<div className="col-3">
<a title={i18n.t('content:review.delete')} className="delete" onClick={this.deleteRecording}></a>
<a title={i18n.t('content:review.redo')} className="record" onClick={this.onRecordButtonClick}></a>
</div>
<div className="col-6">
<div className="review-container">
<ReviewOverlay
activeRecordUser={this.state.authenticatedUser}
record={this.state.activeRecord}
/>
</div>
</div>
{finishContainer}
<div className="col-3">
<div className="target-switch">
<p>Weiter mit der Aufnahme</p>
{targetSwitchElements}
</div>
</div>
</div>
</div>
<div className="upper" ref="upper">
<Menu location={this.props.location} />
<div className="menu">
</div>
</div>
<div className="upperguard" ref="upperguard"></div>
<div className="lower" ref="lower">
<div className="sizing-wrapper">
{usageContent}
</div>
</div>
</div>
);
},
deleteRecording: function(e) {
e.preventDefault();
if(this.props.location && this.props.location.state.userId) {
this.context.router.push({
pathname: "/thread/" + this.props.location.state.userId,
state: this.props.location.state
});
}
else {
this.context.router.push({
pathname: "/profile",
state: this.props.location.state
});
}
},
onRecordButtonClick: function(e) {
e.preventDefault();
this.context.router.push({
pathname: "/record",
state: this.props.location.state
});
},
onThreadCardSelected: function(syntheticEvent, reactId, e) {
var target = syntheticEvent.target.parentNode;
var threadId = target.getAttribute("data-thread-id");
var idx = this.state.selectedThreads.indexOf(threadId);
if(idx != -1) {
this.state.selectedThreads.splice(idx, 1);
this.setState({
selectedThreads: [].concat(this.state.selectedThreads)
});
}
else {
this.setState({
selectedThreads: [threadId].concat(this.state.selectedThreads)
});
}
},
activateThreadShareType: function() {
if(this.state.activeShareType == "thread") {
return;
}
this.setState({
activeShareType: 'thread'
});
},
activateFBShareType: function() {
if(this.state.activeShareType == "facebook") {
return;
}
this.setState({
activeShareType: 'facebook'
});
//this will store the record and generate a shareId
this.getFlux().actions.record.local.saveRecording({
type: "share"
});
/*var state1 = this.context.router.push({
pathname: '/review',
state: {
type: "profile",
role: "main"
}
});*/
//console.log("the state1 is " + state1);
//this.getFlux().actions.record.local.saveRecording(state1);
},
copytoclipboard: function(){
var copyText = document.getElementById("shareLink");
copyText.select();
document.execCommand("copy");
console.log("Copied the text: " + copyText.value);
},
onFinishRecord: function(e) {
if(e.target.classList.contains('inactive')) {
return;
}
if(this.props.location.state && ["profile", "sharereply"].indexOf(this.props.location.state.type) != -1) {
console.log(this.props.location.state);
this.getFlux().actions.record.local.saveRecording(this.props.location.state);
}
else if(this.state.activeShareType == "facebook") {
this.getFlux().actions.record.local.saveRecording({
type: "share"
});
}
else {
var data = {
type: "thread",
threadIds: this.state.selectedThreads
};
//we started recording from a thread, so we pass the userId to be able to return to this thread
//after saving
if(this.props.location.state && this.props.location.state.type == "thread") {
data.userId = this.props.location.state.userId;
}
this.getFlux().actions.record.local.saveRecording(data);
}
}
});
module.exports = Review;
I found my error!
The problem was that I initialized the require('react-share') in a variable reactShare and was using the component as
<FacebookShareButton url={shareLink} quote={title} className="social-media-icon">
<FacebookIcon size={32} round />
</FacebookShareButton>`
Instead, I should have initialized the require statement as
var FacebookShareButton = require('react-share');
Because of not declaring it properly React was yelling on me.
I hope this will save someones precious time. Cheers!

How to handle tab hiding on load and loading content on demand via server call using angular material?

API's used : Angularjs, Angular material for tabs and ui-grid(ui-grid.info)
I have five tabs, currently i am loading all the five tabs using angular material with content as grid from angular-ui-grid; data loaded from backend using external pagination per page data from backend.
HTML Code:
<div cg-busy="{promise:downloadCSVPromise,message:'Downloading...'}">
<div cg-busy="{promise:loadingData,message:'Loading Data...'}">
<section style="min-height: 434px;" class="wrap">
<div ng-cloak>
<md-content>
<md-tabs md-selected="selectedIndex" md-border-bottom md-autoselect md-dynamic-height>
<md-tab id="tab1" ng-disabled="disableParts">
<md-tab-label>Tab 1</md-tab-label>
<md-tab-body>
<div class="custom-csv-link-location"></div>
<div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter ui-grid-auto-resize class="myGrid">
<div class="grid-msg-overlay" ng-hide="!vm.loading">
<div class="msg">
<span>
Loading Data...
<i class="fa fa-spinner fa-spin"></i>
</span>
</div>
</div>
<div class="watermark" ng-show="!gridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab2" ng-disabled="disableService">
<md-tab-label>Service Order</md-tab-label>
<md-tab-body>
<div ui-grid="serviceOrderGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!serviceOrderGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab3" ng-disabled="disableSales">
<md-tab-label>Sales Order</md-tab-label>
<md-tab-body>
<div ui-grid="salesGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!salesGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab4" ng-disabled="disableNC">
<md-tab-label>Non Conformances</md-tab-label>
<md-tab-body>
<div ui-grid="nonconfGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!nonconfGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab5" ng-disabled="disableBOM" md-on-select="resize()">
<md-tab-label>System BOM</md-tab-label>
<md-tab-body>
<div id="bom-charts">
<div class="chartBx bom-pie-chart">
<nvd3 options="pie_options" data="pie_data"></nvd3>
</div>
<div class="chartBx bom-stack-chart">
<nvd3 options="stack_options" data="stack_data"></nvd3>
</div>
<div class="clearfix"></div>
</div>
<div ui-grid="bomGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!bomGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
</md-tabs>
</md-content>
</div>
</section>
</div>
</div>
Script Code:
function partsData(type) {
$scope.serversideFilters = [];
$scope.type=type ? type : "";
var paginationOptions = {
pageNumber: 1,
pageSize: 25,
sort: null
};
var originatorEv;
$scope.openMenu = function ($mdOpenMenu, ev) {
originatorEv = ev;
$mdOpenMenu(ev);
};
$scope.switchTabs = function (row, type) {
console.log('Menu item clicked - ' + row.entity.materialnum);
if(type === "service_order"){
$scope.selectedIndex = 1;
$scope.drillKeyword = row.entity.materialnum;
serviceOrderData('drill');
} else if(type === "sales_order"){
$scope.selectedIndex = 2;
$scope.drillKeyword = row.entity.materialnum;
salesData('drill');
} else if(type === "NC"){
$scope.selectedIndex = 3;
$scope.drillKeyword = row.entity.materialnum;
nonconfData('drill');
} else if(type === "BOM"){
$scope.selectedIndex = 4;
$scope.drillKeyword = row.entity.materialnum;
bomData('drill');
}
};
var fileNm = 'Parts_' + today + '.csv';
$scope.gridOptions = {
enableSelectAll: false,
enableRowSelection: false,
enableRowHeaderSelection: false,
exporterCsvFilename: fileNm,
exporterMenuPdf: false,
enableFiltering: true,
showGridFooter: true,
paginationPageSizes: [25, 50, 75],
paginationPageSize: 25,
useExternalPagination: true,
enableGridMenu: true,
columnDefs: [
{
name: 'materialnum', displayName: 'Part Number', cellClass: '', headerCellClass:'header-server-filtered',enableFiltering: false,width: 150,
cellTemplate: "<div class='ui-grid-cell-contents'><md-menu md-offset='0 45' md-position-mode='target target'><md-button class='md-icon-button' ng-click='grid.appScope.openMenu($mdOpenMenu, $event)'><i class='fa fa-indent'></i></md-button><md-menu-content width='2'><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;service_order&apos;)'>Service Order </md-button></md-menu-item><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;sales_order&apos;)'>Sales Order</md-button></md-menu-item><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;NC&apos;)'>Non Conformances</md-button></md-menu-item><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;BOM&apos;)'>System BOM</md-button></md-menu-item></md-menu-content></md-menu><span title='{{COL_FIELD CUSTOM_FILTERS}}' ng-click='grid.appScope.showAdvanced($event, row, col)' class='partNum'>{{COL_FIELD CUSTOM_FILTERS}}</span></div>"
},
{
name: 'materialdesc', displayName: 'Part Description', headerCellClass: 'header-server-filtered', width: 200,
filter: {
condition: $scope.filterPartDesc
},
cellTemplate: '<div ng-if="row.entity.materialdesc" title="{{row.entity.materialdesc}}" >{{row.entity.materialdesc}}</div><div ng-if="!row.entity.materialdesc"></div>',
},
sparableColumn,
consumableColumn,
cvvColumn,
npiColumn,
criticalColumn,
trColumn,
ipColumn,
faiColumn,
altpartsColumn,
repariableColumn,
{
name: 'onhandstock', displayName: 'On Hand Stock', headerCellClass: $scope.highlightFilteredHeader, enableFiltering: false,
cellTemplate: '<div ng-if="row.entity.onhandstock" class="tcenter">{{row.entity.onhandstock}}</div><div ng-if="!row.entity.onhandstock"></div>'
},
{
name: 'totalstock', displayName: 'Total Stock Limit', headerCellClass: $scope.highlightFilteredHeader, enableFiltering: false,
cellTemplate: '<div ng-if="row.entity.totalstock" class="tcenter">{{row.entity.totalstock}}</div><div ng-if="!row.entity.totalstock"></div>'
}
],
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
/* Facet filter for server side filtering*/
$scope.gridApi.core.on.filterChanged( $scope, function() {
var grid = this.grid;
$scope.serversideFilters = [];
angular.forEach(grid.columns, function(value, key) {
if(value.filters[0].term) {
var dummy = {};
console.log('FILTER TERM FOR ' + value.colDef.name + ' = ' + value.filters[0].term);
dummy['k'] = value.colDef.name;
dummy['v'] = value.filters[0].term;
$scope.serversideFilters.push(dummy);
}
});
getPage();
});
$scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
if (sortColumns.length === 0) {
paginationOptions.sort = null;
} else {
paginationOptions.sort = sortColumns[0].sort.direction;
}
getPage();
});
$scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
paginationOptions.pageNumber = newPage;
paginationOptions.pageSize = pageSize;
getPage();
});
}
}
$scope.filterPartDesc = function(searchTerm, callValue){
console.log('Inside Filter Part Description' +searchTerm );
if(value.filters[0].term) {
var dummy = {};
console.log('FILTER TERM FOR ' + value.colDef.name + ' = ' + value.filters[0].term);
dummy['k'] = value.colDef.name;
dummy['v'] = value.filters[0].term;
$scope.serversideFilters.push(dummy);
}
};
var getPage = function () {
var url = "http://test.server.com:8080/Dash/TestServlet";
var keyword = $scope.keyword ? $scope.keyword : '';
var paramsObj = {};
if($scope.type == "drill"){
keyword = $scope.drillKeyword;
paramsObj['ftype'] = 'exact';
}
paramsObj['query'] = keyword;
paramsObj['start'] = paginationOptions.pageSize * paginationOptions.pageNumber - paginationOptions.pageSize;
paramsObj['rows'] = paginationOptions.pageSize;
if (type && type !== '') {
if (type === 'cvv')
paramsObj[type] = 'YES';
if (type === 'sparable')
paramsObj[type] = 'YES';
if (type === 'consumable')
paramsObj[type] = 'C';
}
angular.forEach($scope.serversideFilters, function(obj){
paramsObj[obj.k] = obj.v;
});
$scope.loadingData = $http.get(url, { params: paramsObj, headers: { 'Content-Type': 'application/json' } })
.then(function (res) {
$scope.gridOptions.totalItems = res.data.numFound;
$scope.gridApi.grid.options.totalItems = res.data.numFound;
$scope.numFound = res.data.numFound;
var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
$scope.filters = res.data.facetFieldsMap;
var dummy = {
label: "",
value: ""
}
$scope.consumableFilter = [];
$scope.sparableFilter = [];
$scope.cvvFilter = [];
$scope.npiFilter = [];
$scope.criticalFilter = [];
$scope.trFilter = [];
$scope.ipFilter = [];
$scope.faiFilter = [];
$scope.altpartsFilter = [];
$scope.repariableFilter = [];
angular.forEach($scope.filters, function (ukey, uvalue) {
if (uvalue === "sparable") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.sparableFilter.push(dummy);
});
}
if (uvalue === "consumable") {
angular.forEach(ukey, function (key, value) {
/*if (value === 'N'){
value = 'NO';
}
if (value === 'Y'){
value = 'YES';
} */
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.consumableFilter.push(dummy);
});
}
if (uvalue === "cvv") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.cvvFilter.push(dummy);
});
}
if (uvalue === "npi") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.npiFilter.push(dummy);
});
}
if (uvalue === "crtclpart") {
angular.forEach(ukey, function (key, value) {
dummy = {};
/*if (value === 'N'){
value = 'NO';
}
if (value === 'Y'){
value = 'YES';
} */
dummy.label = value;
dummy.value = value;
$scope.criticalFilter.push(dummy);
});
}
if (uvalue === "traderstrctd") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.trFilter.push(dummy);
});
}
if (uvalue === "ipsnstv") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.ipFilter.push(dummy);
});
}
if (uvalue === "fai") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.faiFilter.push(dummy);
});
}
if (uvalue === "alternatepart") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.altpartsFilter.push(dummy);
});
}
if (uvalue === "reprblcd") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.repariableFilter.push(dummy);
});
}
});
sparableColumn.filter.selectOptions = $scope.sparableFilter;
consumableColumn.filter.selectOptions = $scope.consumableFilter;
cvvColumn.filter.selectOptions = $scope.cvvFilter;
npiColumn.filter.selectOptions = $scope.npiFilter;
criticalColumn.filter.selectOptions = $scope.criticalFilter;
trColumn.filter.selectOptions = $scope.trFilter;
ipColumn.filter.selectOptions = $scope.ipFilter;
faiColumn.filter.selectOptions = $scope.faiFilter;
altpartsColumn.filter.selectOptions = $scope.altpartsFilter;
repariableColumn.filter.selectOptions = $scope.repariableFilter;
$scope.gridOptions.data = res.data.partSearchList;
if ($scope.gridOptions.data.length === 0) {
$scope.gridOptions.enablePaginationControls = false;
}
});
};
$scope.toggleFilterRow = function () {
$scope.gridOptions.enableFiltering = !$scope.gridOptions.enableFiltering;
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
};
getPage();
}
Currently i am loading all the tabs with all the hits going to backend to fetch data but as per the requirement i need to change like below:
Only one tab will be loaded as per user selects in a dropdown to load the data and then inside the loaded tab we have links to other tab which will dynamically load the remaining tab/s on demand
I tried to hide or disable the material tabs but was getting error on load of the page on below lines :
$scope.gridApi.grid.options.totalItems = res.data.numFound;
I kept the loading of particular tab conditionally but then the HTML had the gridOptions defined and script was not initialized with the gridOptions it also threw error.
Finally i had tried below as well but didnt worked out.
$scope.serviceOrderGridOptions = {};
$scope.gridOptions = [];
$scope.serviceOrderGridOptions.data = [];
How can we make a tab load on demand with no issues on load of the page and also how to load the ui-grid inside it.
Appreciate your help!

InfiniteScroll - AngularJS not working

Edit:
Just for checking purposes, I also did a console.log inside the nextPage function, to check if it's being triggered:
$scope.nextPage = function() {
var captureLength = $scope.captures.length;
console.log('TRIGGER');
if($scope.busy) {
return;
}
...
}
};
And it seems I'm getting a infinite loop, but I can't see why.
=================================
I'm trying to implement infinitescroll into a view but for some reason it's only loading the initial 4 images and not triggering the rest.
Here is my code:
CTRL:
/* ----------------------- Variables ----------------------- */
$scope.auth = auth;
$scope.captures = [];
$scope.following = [];
$scope.allData = [];
$scope.busy = true;
var page = 0;
var step = 4;
$scope.nextPage = function() {
var captureLength = $scope.captures.length;
if($scope.busy) {
return;
}
$scope.busy = true;
$scope.captures = $scope.captures.concat($scope.allData.splice(page * step, step));
page++;
$scope.busy = false;
if($scope.captures.length === 0) {
$scope.noMoreData = true;
}
};
/* ----------------------- Process Data ----------------------- */
$q.all({follows: findFollow(), users: getUsers(), captures: getAllCaptures()}).then(function(collections) {
var follows = collections.follows;
var users = collections.users;
var captures = collections.captures;
follows.filter(function(follow) {
return follow.follower_id === auth.profile.user_id;
}).forEach(function(follow) {
users.filter(function(user) {
return user.user_id === follow.followed_id;
}).forEach(function(user) {
$scope.following.push(user);
});
});
follows.filter(function(follow) {
return follow.follower_id === auth.profile.user_id;
}).forEach(function(follow) {
captures.filter(function(capture){
return follow.followed_id === capture.userId;
}).forEach(function(capture){
console.log(capture);
$scope.allData.push(capture);
});
});
$scope.nextPage();
$scope.busy = false;
});
/* ----------------------- Retrieve Services - Data ----------------------- */
function findFollow() {
return userApi.findFollow().then(function(res) {
return res.data;
});
}
function getUsers() {
return userApi.getUsers().then(function(res) {
return res.data.users;
});
}
function getAllCaptures() {
return captureApi.getAllCaptures().then(function(res) {
return res.data;
});
}
Partial:
<div class="col-md-8">
<div class="well main-well">
<h3 class="page-header-h3">Following Dashboard:</h3>
<hr />
<h4 align="center" ng-show="!captures.length">
<strong>The people that you are following, have not posted anything yet.. Yikes!</strong>
<br /><br />
Quickly, go follow more people!</h4>
<div class="row" infinite-scroll="nextPage()" infinite-scroll-disabled="busy || noMoreData" infinite-scroll-distance="0.1">
<ul class="dynamic-grid" angular-grid="captures" ag-id="gallery">
<li data-ng-repeat="capture in captures | orderBy :'created_at':true" class="grid">
<a ui-sref="detail({id: capture._id})">
<img ng-src="{{capture.picture}}" class="grid-img" />
<span class="follow-capture-info">
<span class="follow-capture-name"><span class="glyphicon glyphicon-user"></span>
{{capture.author}}
<span class="following-capture-time">ยท
<span class="glyphicon glyphicon-time"></span>
<span am-time-ago="capture.created_at"></span>
</span>
</span>
</span>
</a>
</li>
</ul>
</div>
<div ng-show="busy">Loading more...</div>
</div>
Anyone know where I went wrong?
Thanks.

{{numPages}} not being calculated by pagination directive

I was under the impression with the pagination directive that the {{numPages}} value would be calculated by the directive. It isn't returning anything for me.
Is there anything I am missing to get this working properly? I don't want to have to calculate it, if the directive is supposed to be doing this for me. Otherwise paging is working great.
<pagination
total-items="totalItems"
ng-model="currentPage"
max-size="maxSize"
items-per-page="itemsPerPage"
class="pagination-sm"
boundary-links="true" rotate="false">
</pagination>
<table class="table table-striped">
<tr>
<td style="width:150px;">GPT ID</td>
<td style="width:250px;">Therapy Area</td>
<td style="width:450px;">GPT Description</td>
<td style="width:150px;">Actions</td>
</tr>
<tr ng-repeat="prGpt in prGpts | orderBy:['therapyArea.therapyArea','gptDesc'] | startFrom:(currentPage -1) * itemsPerPage | limitTo: itemsPerPage">
<td>{{prGpt.id}}</td>
<td>
<span ng-if="!prGpt.editMode">{{prGpt.therapyArea.therapyArea}}</span>
<span ng-if="prGpt.editMode && !createMode">
<select class="form-control" style="width:150px;" ng-model="selectedGpt.therapyArea" ng-options="item as item.therapyArea for item in therapyAreas"/>
</span>
</td>
<td>
<span ng-if="!prGpt.editMode">{{prGpt.gptDesc}}</span>
<span ng-if="prGpt.editMode && !createMode"><input class="form-control" type="text" style="width:400px;" ng-model="selectedGpt.gptDesc" /></span>
</td>
<td>
<span ng-if="!prGpt.editMode" class="glyphicon glyphicon-pencil" ng-click="copySelectedGpt(prGpt);beginEditGpt()"/>
<span ng-if="prGpt.editMode && !createMode" class="glyphicon glyphicon-floppy-disk" ng-click="saveEditGpt()"/>
<span ng-if="prGpt.editMode && !createMode" class="glyphicon glyphicon-thumbs-down" ng-click="cancelEditGpt()"/>
<span ng-if="!prGpt.editMode && !createMode" class="glyphicon glyphicon-remove-circle" ng-click="copySelectedGpt(prGpt);openDeleteDialog()"/>
<span><a ng-href="#!pr/gptProjects/{{prGpt.id}}">Edit Projects</a>
</span>
</tr>
</table>
<br/>
<pre>Page: {{currentPage}} / {{numPages}}</pre>
</div>
controller:
// GPT List Controller
.controller('prGPTCtrl',['$scope', '$modal', '$dialog', 'Restangular', 'prTAService', 'prGPTService', function($scope, $modal, $dialog, Restangular, prTAService, prGPTService) {
// window.alert('prGPTCtrl');
$scope.prGpts = {};
$scope.therapyAreas = {};
$scope.createMode = false;
$scope.selectedGpt = {};
$scope.newGpt = {};
// pagination
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
$scope.maxSize = 20;
$scope.totalItems = $scope.prGpts.length;
Restangular.setBaseUrl('resources/pr');
//call the TA service to get the TA list for the drop down lists
//and then get the gpt list once successful
prTAService.getTAs().then(function(tas) {
$scope.therapyAreas = tas;
prGPTService.getGPTs().then(function(gpts) {
//window.alert('prGPTCtrl:getGPTs');
$scope.prGpts = gpts;
});
});
$scope.$watch('prGpts.length', function(){
$scope.totalItems = $scope.prGpts.length;
});
/*
* Take a copy of the selected GPT to copy in
*/
$scope.copySelectedGpt = function(prGpt) {
$scope.selectedGpt = Restangular.copy(prGpt);
};
$scope.beginEditGpt = function() {
var gpt = {};
var ta = {};
var gpt;
for(var i = 0; i < $scope.prGpts.length;i++) {
gpt = $scope.prGpts[i];
gpt.editMode = false;
}
var index = _.findIndex($scope.prGpts, function(b) {
return b.id === $scope.selectedGpt.id;
});
gpt = $scope.prGpts[index];
gpt.editMode = true;
var taIndex = _.findIndex($scope.therapyAreas, function(b) {
return b.id === $scope.selectedGpt.therapyArea.id;
});
ta = $scope.therapyAreas[taIndex];
$scope.selectedGpt.therapyArea = ta;
$scope.createMode = false;
};
$scope.cancelEditGpt = function() {
var gpt;
for(var i = 0; i < $scope.prGpts.length;i++) {
gpt = $scope.prGpts[i];
gpt.editMode = false;
}
var index = _.findIndex($scope.prGpts, function(b) {
return b.id === $scope.selectedGpt.id;
});
$scope.selectedGpt = null;
$scope.prGpts[index].editMode = false;
};
$scope.saveEditGpt = function() {
$scope.selectedGpt.save().then(function (gpt) {
// find the index in the array which corresponds to the current copy being edited
var index = _.findIndex($scope.prGpts, function(b) {
return b.id === $scope.selectedGpt.id;
});
$scope.prGpts[index] = $scope.selectedGpt;
$scope.prGpts[index].editMode = false;
$scope.selectedGpt = null;
},
function(err) {
window.alert('Error occured: ' + err);
}
);
};
// create a new GPT
$scope.createGpt = function() {
$scope.createMode = true;
var gpt;
for(var i = 0; i < $scope.prGpts.length;i++) {
gpt = $scope.prGpts[i];
gpt.editMode = false;
}
};
$scope.saveNewGpt = function() {
Restangular.all('/gpt/gpts').post($scope.newGpt).then(function(gpt) {
$scope.newGpt = {};
$scope.prGpts.push(gpt);
$scope.createMode = false;
// window.alert('created new GPT ' + gpt.gptDesc + ' with id ' + gpt.id);
});
};
$scope.openDeleteDialog = function() {
var title = "Please confirm deletion of GPT " + $scope.selectedGpt.gptDesc;
var msg = "<b>Delete GPT? Please confirm...</b>";
var btns = [{result:'CANCEL', label: 'Cancel'},
{result:'OK', label: 'OK', cssClass: 'btn-primary'}];
$dialog.messageBox(title, msg, btns, function(result) {
if (result === 'OK') {
$scope.deleteGpt();
}
});
};
$scope.deleteGpt = function() {
$scope.selectedGpt.remove().then(function() {
$scope.prGpts = _.without($scope.prGpts, _.findWhere($scope.prGpts, {id: $scope.selectedGpt.id}));
$scope.selectedGpt = null;
},
function() {
window.alert("There was an issue trying to delete GPT " + $scope.selectedGpt.gptDesc);
}
);
};
}]);
I have a startFrom filter.
.filter('startFrom', function () {
return function (input, start) {
if (input === undefined || input === null || input.length === 0
|| start === undefined || start === null || start.length === 0 || start === NaN) return [];
start = +start; //parse to int
try {
var result = input.slice(start);
return result;
} catch (e) {
// alert(input);
}
};
})
Regards
i
Looks like you're just missing num-pages="numPages" on your <pagination> tag. Essentially you have to provide a variable to pagination in which to return the number of pages. This is done via num-pages
<pagination
num-pages="numPages" <!-- Add this here -->
total-items="totalItems"
ng-model="currentPage"
max-size="maxSize"
items-per-page="itemsPerPage"
class="pagination-sm"
boundary-links="true" rotate="false">
</pagination>

Resources