Open a modal from another modal using bootstrap and angularJs - angularjs

I am trying to open a modal by clicking on link on the another modal.
Here is my code:
.controller('payoutCtrl', ['$scope', '$uibModal', 'payoutService', function($scope, $uibModal, payoutService) {
console.log('payout');
var vm = this;
$scope.openAddPayout = function(){
var modalInstance = $uibModal.open({
templateUrl: "app/modules/homePage/payment/Payout/addPayoutMethod.tmpl.html",
controller: 'payoutModalCtrl',
controllerAs: 'vm',
size: 'lg',
resolve: {
payoutMethods: function(){
return vm.payoutMethods;
}
}
});
modalInstance.result.then(function() {
console.log('success');
}, function(){
//Do stuff with respect to dismissal
console.log('error');
$state.go('homePage.payment.payout');
});
}
}])
the upper modal is getting open and calling the below controller as well.
.controller('payoutModalCtrl', ['$rootScope', '$scope', '$uibModal', '$uibModalInstance', 'payoutMethods', function($rootScope, $scope, $uibModal, $uibModalInstance, payoutMethods){
var vm = this;
vm.payoutMethods = payoutMethods;
vm.pay = function(method){
console.log(method);
vm.templateUrl;
if(method == 1){
vm.templateUrl = "app/modules/homePage/payment/Payout/check.tmpl.html"
}
else if(method == 2){
vm.templateUrl = "app/modules/homePage/payment/Payout/payPal.tmpl.html"
}
else if(method == 3){
vm.templateUrl = "app/modules/homePage/payment/Payout/directDeposite.tmpl.html"
}
console.log(vm.templateUrl);
var modalScope = $rootScope.$new();
modalScope.modalInstance = $uibModal.open({
templateUrl:vm.templateUrl,
controller: 'addPayoutDetailModalCtrl',
size: 'sm'
});
}
}])
on calling vm.pay function, another modal should open, where I am getting failed. And the best part I am not able to debug is it is not giving any error.
But from Network and Console from developer tool I have noticed that template is getting called but the controller is not getting call.
.controller('addPayoutDetailModalCtrl', ['$uibModalInstance', 'payoutMethods', function($uibModalInstance, payoutMethods){
// $uibModalInstance.close();
console.log('addPayoutDetailModalCtrl call');
}]);
So I am getting the first modal, but from that controller I am not able to open another modal.
Can anyone help!

I have updated the controllers jsfiddle
.controller('payoutCtrl', ['$scope', '$uibModal', function($scope, $uibModal) {
console.log('payoutCtrl');
var vm = this;
$scope.openAddPayout = function(){
var modalInstance = $uibModal.open({
templateUrl: "addPayoutMethod.tmpl.html",
controller: 'payoutModalCtrl',
controllerAs: 'vm',
size: 'lg',
resolve: {
payoutMethods: function(){
return vm.payoutMethods;
}
}
});
modalInstance.result.then(function() {
console.log('success');
}, function(){
console.log('error');
});
}
}])
.controller('payoutModalCtrl', ['$rootScope', '$scope', '$uibModal', '$uibModalInstance', 'payoutMethods', function($rootScope, $scope, $uibModal, $uibModalInstance, payoutMethods){
var vm = this;
console.log('payoutModalCtrl');
vm.payoutMethods = payoutMethods;
$scope.pay = function(method){
vm.templateUrl = "check.tmpl.html";
console.log(vm.templateUrl);
var modalScope = $rootScope.$new();
modalScope.modalInstance = $uibModal.open({
templateUrl:vm.templateUrl,
controller: 'addPayoutDetailModalCtrl',
size: 'sm'
});
}
}])
.controller('addPayoutDetailModalCtrl', ['$uibModalInstance', function($uibModalInstance){
console.log('addPayoutDetailModalCtrl call');
}]);

Here is an example I have used. I deleted a bunch of stuff just to give you an idea. And the main idea is to hide sections you don't want to show, and to show the sections you want to:
Controller:
(function () {
'use strict';
angular.module('app.createReportSchedule')
.controller('createReportScheduleController', createReportScheduleController);
createReportScheduleController.$inject = ['logger', 'manageReportSchedulesFactory', '$scope', '$modalInstance'];
function createReportScheduleController(logger, manageReportSchedulesFactory, $scope, $modalInstance) {
var vm = $scope;
vm.isUpdate = false;
vm.isUpdateNext = false;
vm.schedule = vm.$parent.schedule;
vm.ReportSchedule = {};
vm.SchedulingOptions = {};
vm.SchedulingUpdateOptions = {};
vm.ReportFilters = {};
vm.showReportSchedule = true;
// Reports Begin
vm.showMasterCallReport = false;
vm.showTimeAndMileage = false;
vm.showAllCallsRemote = false;
vm.showAllCalls = false;
// Reports End
vm.showReportScheduleUpdate = false;
// Report Modal Data
vm.MasterCallReportData = null;
vm.TimeAndMileageReportData = null;
vm.allCallsRemoteReportData = null;
// Modal Back Function
vm.back = function () {
if (vm.showReportSchedule || vm.showReportScheduleUpdate) {
$modalInstance.dismiss('cancel');
}
else if (vm.showMasterCallReport) {
vm.showReportSchedule = true;
vm.showMasterCallReport = false;
}
else if (vm.showTimeAndMileage) {
vm.showReportSchedule = true;
vm.showTimeAndMileage = false;
}
else if (vm.showAllCallsRemote) {
vm.showReportSchedule = true;
vm.showAllCallsRemote = false;
}
};
// Create Report Schedule
vm.next = function () {
if (vm.showReportSchedule) {
if (this.formCreateReportSchedule.$valid) {
vm.showReportSchedule = false;
vm.isUpdateNext = false;
if (vm.ReportSchedule.ReportTemplate.ReportTemplateId == 7) {
vm.showMasterCallReport = true;
return masterCallReportFactory.getData().then(function (data) {
if (logger.displayCommandResult(data)) {
vm.MasterCallReportData = data.Records[0];
}
});
}
if (vm.ReportSchedule.ReportTemplate.ReportTemplateId == 8) {
vm.showTimeAndMileage = true;
return timeAndMileageReportFactory.getData().then(function (data) {
if (logger.displayCommandResult(data)) {
vm.TimeAndMileageReportData = data.Records[0];
}
});
}
if (vm.ReportSchedule.ReportTemplate.ReportTemplateId == 9) {
vm.showAllCallsRemote = true;
return allCallsRemoteReportFactory.getData().then(function (data) {
if (logger.displayCommandResult(data)) {
vm.allCallsRemoteReportData = data.Records[0];
}
});
}
if (vm.ReportSchedule.ReportTemplate.ReportTemplateId == 20) {
vm.formSubmmision = true;
return vm.postScheduleCreationData();
}
} else {
logger.error('Error: Validation failed. Please correct data and try again');
}
}
else if (vm.isUpdate === true) {
if (this.formUpdateReportSchedule.$valid) {
vm.showReportScheduleUpdate = false;
vm.isUpdate = false;
vm.isUpdateNext = true;
if (vm.schedule.ReportTemplate.ReportTemplateId == 7) {
vm.showMasterCallReport = true;
}
if (vm.schedule.ReportTemplate.ReportTemplateId == 8) {
vm.showTimeAndMileage = true;
}
} else {
logger.error('Error: Validation failed. Please correct data and try again');
}
}
else if (vm.isUpdateNext === true) {
if (vm.showMasterCallReport || vm.showTimeAndMileage || vm.showAllCallsRemote || vm.showAllCalls || vm.showAllCallsSLALeft
|| vm.showBreakFix || vm.showCallAssetLine || vm.showDailyStatus || vm.showDailyStatusExtended || vm.showHighPriorityCalls
|| vm.showSLAMasterCalls || vm.showStockMovement) {
// Report Forms
if (this.masterCallReport.$valid || this.timeAndMileageReport.$valid || this.allCallsRemoteReport.$valid || this.allCallsReport.$valid
|| this.allCallsSLALeftReport.$valid || this.callAssetLinesReport.$valid || this.dailyStatusReport.$valid || this.dailyStatusExtendedReport.$valid
|| this.reportHighPriorityCalls.$valid || this.slaMasterCallReport.$valid || this.stockMovementReport.$valid) {
vm.formSubmmision = true;
console.log(vm.schedule);
return vm.postScheduleUpdateData();
}
} else {
return logger.error('Error: Validation failed. Please correct data and try again');
}
}
else if (vm.isUpdateNext === false) {
if (vm.showMasterCallReport || vm.showTimeAndMileage || vm.showAllCallsRemote || vm.showAllCalls || vm.showAllCallsSLALeft
|| vm.showBreakFix || vm.showCallAssetLine || vm.showDailyStatus || vm.showDailyStatusExtended || vm.showHighPriorityCalls
|| vm.showSLAMasterCalls || vm.showStockMovement) {
// Report Forms
if (this.masterCallReport.$valid || this.timeAndMileageReport.$valid || this.allCallsRemoteReport.$valid || this.allCallsReport.$valid
|| this.allCallsSLALeftReport.$valid || this.callAssetLinesReport.$valid || this.dailyStatusReport.$valid || this.dailyStatusExtendedReport.$valid
|| this.reportHighPriorityCalls.$valid || this.slaMasterCallReport.$valid || this.stockMovementReport.$valid) {
vm.formSubmmision = true;
return vm.postScheduleCreationData();
}
} else {
return logger.error('Error: Validation failed. Please correct data and try again');
}
}
};
}
})();
HTML:
<!-- Begin Report Schedule Create-->
<form name="formCreateReportSchedule" novalidate ng-show="showReportSchedule">
<div class="modal-header">
<h3 class="modal-title">Report Scheduling Options</h3>
</div>
<div class="modal-body">
<!-- New Modal -->
<div class="row">
<!-- Report Name -->
<div class="col-md-6">
<label>Report Schedule Name:</label>
<div class="input-text">
<input type="text" name="iScheduleName" ng-model="ReportSchedule.ScheduleName" ng-required="true" />
<div class="fadeInOut" ng-class="{error : iScheduleNameError}" ng-mouseenter="iScheduleNameError = true" ng-mouseleave="iScheduleNameError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iScheduleName.$touched) && formCreateReportSchedule.iScheduleName.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Enter a Schedule Name</span>
</p>
</div>
</div>
</div>
</div>
<!-- Report Template -->
<div class="col-md-6">
<label>Report Type</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Report Name"
ng-model="ReportSchedule.ReportTemplate"
ng-options="SchedulingOptions.SelectableReportTemplates"
cc-fields="ReportTemplateName"
cc-key-field="ReportTemplateId"
cc-allow-search="SchedulingOptions.SelectableReportTemplates != null && SchedulingOptions.SelectableReportTemplates.length > 5"
ng-required="true"
name="iReportTemplate">
</cc-dropdown>
<div class="fadeInOut" ng-class="{error : iReportTemplateError}" ng-mouseenter="iReportTemplateError = true" ng-mouseleave="iReportTemplateError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iReportTemplate.$touched) && formCreateReportSchedule.iReportTemplate.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Select a Template</span>
</p>
</div>
</div>
</div>
</div>
<!-- Hours -->
<div class="col-md-6">
<label>Execution Time</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Report Time"
ng-model="ReportSchedule.ExecutionTime"
ng-options="SelectableExecutionTimes"
cc-fields="<self>"
cc-allow-search="true"
ng-required="true"
name="iExecutionTime">
</cc-dropdown>
<div class="fadeInOut" ng-class="{error : iExecutionTimeError}" ng-mouseenter="iExecutionTimeError = true" ng-mouseleave="iExecutionTimeError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iExecutionTime.$touched) && formCreateReportSchedule.iExecutionTime.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Select an Execution Time</span>
</p>
</div>
</div>
</div>
</div>
<!-- Reporting Period -->
<div class="col-md-6">
<label>Period</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Reporting Period"
ng-model="ReportSchedule.ReportPeriod"
ng-options="SchedulingOptions.SelectableReportingPeriods"
cc-fields="ReportPeriodName"
cc-key-field="ReportPeriodId"
cc-allow-search="SchedulingOptions.SelectableReportPeriods != null && SchedulingOptions.SelectableReportPeriods.length > 5"
ng-required="true"
name="iReportPeriod">
</cc-dropdown>
<div class="fadeInOut" ng-class="{error : iReportPeriodError}" ng-mouseenter="iReportPeriodError = true" ng-mouseleave="iReportPeriodError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iReportPeriod.$touched) && formCreateReportSchedule.iReportPeriod.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Select a Reporting Period</span>
</p>
</div>
</div>
</div>
</div>
<!-- Frequency -->
<div class="col-md-6">
<label>Frequency</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Report Frequency"
ng-model="ReportSchedule.ReportFrequency"
ng-options="SchedulingOptions.SelectableReportFrequencies"
ng-change="frequencyChanged()"
cc-fields="ReportFrequencyName"
cc-key-field="ReportFrequencyId"
cc-allow-search="SchedulingOptions.SelectableReportFrequencies != null && SchedulingOptions.SelectableReportFrequencies.length > 5"
ng-required="true"
name="iReportFrequency">
</cc-dropdown>
<div class="fadeInOut" ng-class="{error : iReportFrequencyError}" ng-mouseenter="iReportFrequencyError = true" ng-mouseleave="iReportFrequencyError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iReportFrequency.$touched) && formCreateReportSchedule.iReportFrequency.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Select a Report Frequency</span>
</p>
</div>
</div>
</div>
</div>
<!-- Frequency Options -->
<div class="col-md-6">
<label>Frequency Options</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Report Frequency Option"
ng-model="ReportSchedule.ReportFrequencyOption"
ng-options="FrequencyOptions"
ng-disabled="FrequencyOptions.length == 0"
cc-fields="ReportFrequencyOptionName"
cc-key-field="ReportFrequencyOptionId"
cc-allow-search="SchedulingOptions.SelectableReportFrequencyOptions != null && SchedulingOptions.SelectableReportFrequencyOptions.length > 5"
ng-required="FrequencyOptions.length != 0"
name="iReportFrequencyOption">
</cc-dropdown>
<div class="fadeInOut" ng-class="{error : iReportFrequencyOptionError}" ng-mouseenter="iReportFrequencyOptionError = true" ng-mouseleave="iReportFrequencyOptionError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iReportFrequencyOption.$touched) && formCreateReportSchedule.iReportFrequencyOption.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Select a Report Frequency Option</span>
</p>
</div>
</div>
</div>
</div>
<!-- Email -->
<div class="col-md-12">
<label>Recipient Email:</label>
<div class="input-text">
<input type="text" name="iEmail" ng-required="true" ng-model="ReportSchedule.EmailRecipients" />
<div class="fadeInOut" ng-class="{error : iEmailError}" ng-mouseenter="iEmailError = true" ng-mouseleave="iEmailError = false" ng-show="(formCreateReportSchedule.$submitted || formCreateReportSchedule.iEmail.$touched) && formCreateReportSchedule.iEmail.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please Enter a Recipient Email Address</span>
</p>
</div>
</div>
</div>
</div>
</div><!-- row -->
</div> <!--body-->
<div class="modal-footer">
<button class="btn btn-warning left" ng-click="back()" ng-disabled="formSubmmision">Cancel</button>
<button class="btn btn-primary right" type="submit" ng-click="next()" ng-disabled="formSubmmision">Next</button>
</div>
</form>
<!-- Selected Report Settings: Master Call Report -->
<form name="masterCallReport" novalidate ng-show="showMasterCallReport">
<div class="modal-header">
<h3 class="modal-title">Schedule: Master Call Report</h3>
</div>
<div class="modal-body">
<div class="row">
<!-- Customer -->
<div class="col-md-6">
<label>Customer</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select a Customer"
ng-model="MasterCallReportData.Customer"
ng-options="MasterCallReportData.SelectableCustomer"
cc-fields="CustomerName"
cc-key-field="CustomerId"
cc-allow-search="MasterCallReportData.SelectableCustomer != null && MasterCallReportData.SelectableCustomer.length > 5"
name="iCustomer">
</cc-dropdown>
</div>
</div>
<!-- Resolver Group -->
<div class="col-md-6">
<label>Resolver Group</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="ALL Resolver Groups"
ng-model="MasterCallReportData.ResolverGroup"
ng-options="MasterCallReportData.SelectableResolverGroup"
cc-fields="ResolverGroupDescription"
cc-key-field="ResolverGroupId"
cc-allow-search="MasterCallReportData.SelectableResolverGroup != null && MasterCallReportData.SelectableResolverGroup.length > 5"
name="iResolverGroup">
</cc-dropdown>
</div>
</div>
<!-- Region -->
<div class="col-md-6">
<label>Region</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="ALL Regions"
ng-model="MasterCallReportData.Region"
ng-options="MasterCallReportData.SelectableRegion"
cc-fields="RegionDescription"
cc-key-field="RegionId"
cc-allow-search="MasterCallReportData.SelectableRegion != null && MasterCallReportData.SelectableRegion.length > 5"
name="iRegion">
</cc-dropdown>
</div>
</div>
<!-- Status -->
<div class="col-md-6">
<label>Status</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Open"
ng-model="MasterCallReportData.CallStatus"
ng-options="MasterCallReportData.SelectableStatus"
cc-fields="Status + ' - ' + Reason"
cc-key-field="CallStatusId"
cc-allow-search="MasterCallReportData.SelectableStatus != null && MasterCallReportData.SelectableStatus.length > 5"
name="iStatus">
</cc-dropdown>
</div>
</div>
<!-- Affected End User -->
<div class="col-md-6">
<label>Affected End User</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select a Contact Person"
ng-model="MasterCallReportData.AffectedEndUser"
ng-options="MasterCallReportData.SelectableAffectedEndUser"
cc-fields="FullName"
cc-key-field="ContactPersonId"
cc-allow-search="MasterCallReportData.SelectableAffectedEndUser != null && MasterCallReportData.SelectableAffectedEndUser.length > 5"
name="iAffectedEndUser">
</cc-dropdown>
</div>
</div>
<!-- Resolution Method -->
<div class="col-md-6">
<label>Resolution Method</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="ALL Method"
ng-model="MasterCallReportData.ResolutionMethod"
ng-options="MasterCallReportData.SelectableResolutionMethod"
cc-fields="ResolutionMethodDescription"
cc-key-field="ResolutionMethodId"
cc-allow-search="false"
name="iResolutionMethod">
</cc-dropdown>
</div>
</div>
<!-- SLA Filter -->
<div class="col-md-6">
<label>SLA Filter</label>
<div class="input-text">
<input type="text" name="iSLAFilter" ng-model="MasterCallReportData.SLAFilter" />
</div>
</div>
<!-- Logged By -->
<div class="col-md-6">
<label>Logged By</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select an Employee"
ng-model="MasterCallReportData.LoggedBy"
ng-options="MasterCallReportData.SelectableLoggedBy"
cc-fields="FullName"
cc-key-field="EmployeeId"
cc-allow-search="MasterCallReportData.SelectableLoggedBy != null && MasterCallReportData.SelectableLoggedBy.length > 5"
name="iLoggedBy">
</cc-dropdown>
</div>
</div>
<!-- Call Priority -->
<div class="col-md-6">
<label>Call Priority</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="ALL Priorities"
ng-model="MasterCallReportData.Priority"
ng-options="MasterCallReportData.SelectableCallPriority"
cc-fields="CallPriorityDescription"
cc-key-field="CallPriorityId"
cc-allow-search="false"
name="iPriority">
</cc-dropdown>
</div>
</div>
<!-- SLA Breaching Warning -->
<div class="col-md-6">
<label>SLA Breaching Warning</label>
<div class="input-switch">
<input id="toggle-2" class="toggle toggle-yes-no" type="checkbox" ng-model="MasterCallReportData.SLABreachWarning">
<label for="toggle-2" data-on="Yes" data-off="No"></label>
</div>
</div>
<!-- Logged -->
<div class="col-md-6">
<label>Logged</label>
<div class="input-switch">
<input id="toggle-3" class="toggle toggle-yes-no" type="checkbox" ng-model="MasterCallReportData.Logged">
<label for="toggle-3" data-on="Yes" data-off="No"></label>
</div>
</div>
<!-- Resolved -->
<div class="col-md-6">
<label>Resolved</label>
<div class="input-switch">
<input id="toggle-4" class="toggle toggle-yes-no" type="checkbox" ng-model="MasterCallReportData.Resolved">
<label for="toggle-4" data-on="Yes" data-off="No"></label>
</div>
</div>
</div><!-- Row End-->
</div>
<div class="modal-footer">
<button class="btn btn-warning left" ng-click="back()" ng-disabled="formSubmmision">Back</button>
<button class="btn btn-primary right" type="submit" ng-click="next()" ng-disabled="formSubmmision">Next</button>
</div>
</form>

Related

two way binding not working even with dot notation

I'm starting with AngularJS and I am using a controller variable to navigate an array of questions, and it is working when using nextQuestion function, index gets updated and the next question is shown in the view, but if I try to obtain the same value (index) in a different function, it always returns 0.
I have seen on other questions that you should use an object to contain the variable to not manipulate primitive types directly in the controller, but it still does not work.
My controller:
myApp.controller('SurveyController',['$scope','$http', '$location','$routeParams','surveyMetrics','DataService',function($scope,$http, $location,$routeParams,surveyMetrics,DataService){
console.log('LOADED QUIZ CONTROLLER');
var vm = this;
vm.scope = {
index: 0
};
vm.surveyMetrics = surveyMetrics;
vm.surveyQuestions = DataService.surveyQuestions;
vm.DataService = DataService;
/*
vm.getQuestions = function(){
$http.get('/api/questions').then(function(response){
$scope.questions = response.data;
});
}
*/
/*
vm.activateSurvey = function(){
surveyMetrics.changeState(true);
}
*/
vm.getCurrentIndex = function(){
return vm.scope.index;
}
vm.nextQuestion = function () {
console.log('NEXT QUESTION!');
console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
var currentIndex = vm.getCurrentIndex();
var newIndex = currentIndex+1;
scope = {};
if (currentIndex == vm.surveyQuestions.length) {
newIndex = vm.surveyQuestions.length -1;
}
vm.scope.index = newIndex;
console.log('Inside Object: '+vm.scope)
console.log('vm.index'+vm.scope.index);
console.log('vm.indexFunction'+vm.getCurrentIndex());
}
/*
vm.previousQuestion = function () {
console.log('PREVIOUS QUESTION!');
console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
if (vm.scope.index == 0) {
vm.scope.index = 0;
}else{
vm.scope.index--;
}
}
*/
vm.activeSurveyQuestion = function(questionId,index){
console.log('question id and index',questionId,index);
if (questionId == index) {
var navBtn = document.getElementById('navBtn_'+index);
navBtn.classList.add('active');
}
}
vm.navigateSurvey = function () {
var answerPane = document.getElementById('answer-pane');
document.onkeydown = function (e) {
console.log('INSIDE KEYDOWN: ')
e.preventDefault();
var pressedKey = e.keyCode;
console.log('PRESSED KEY IN SURVEY: ' + pressedKey);
if (pressedKey === rightArrow) {
console.log('survey - right arrow pressed');
document.getElementById('nextQuestionBtn').click();
console.log('FUCKING INDEX FML!: '+vm.getCurrentIndex()+' | '+vm.scope.index);
var questionType = DataService.getQuestionType(vm.scope.index);
console.log('Survey Controller: question type: '+questionType);
}
if (pressedKey === leftArrow) {
console.log('survey - left arrow pressed');
document.getElementById('previousQuestionBtn').click();
}
(...)
My View:
<!--Satisfaction Survey-->
<div ng-controller="SurveyController as survey" ng-init="survey.getSurvey();">
<!--
<p ng-repeat="question in survey.surveyQuestions" ng-show ="survey.surveyMetrics.surveyActive">
{{question.question}}
</p>
-->
<!--Survey Modal -->
<div class="modal fade" id="surveyModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="text-center"> Customer Satisfaction Survey</div>
<div class="modal-header">
<h4 class="modal-title">{{survey.surveyQuestions[survey.getCurrentIndex()].question}}</h4>
</div>
<div class="modal-body survey" id="answer-pane">
<div class="row">
<div class="col-sm-2 survey-left-arrow" ng-click="survey.previousQuestion();" id="previousQuestionBtn">
<p>‹</p>
</div>
<div class="col-sm-8">
<!-- <p ng-repeat="answer in survey.surveyQuestions[survey.index].answers">{{answer}}</p> -->
<p ng-repeat="answer in survey.surveyQuestions[survey.getCurrentIndex()].answers">
<button type="button" class="btn" id="answerId_{{survey.getCurrentIndex()}}"
ng-class="{'survey-check-box': (survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'),
'survey-btn_{{($index+1)}}': (survey.surveyQuestions[survey.getCurrentIndex()].type === 'SingleChoice')}">
<input type="checkbox" ng-if="survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'"> {{answer}}
</button>
</p>
</div>
<div class="col-sm-2 survey-right-arrow " ng-click="survey.nextQuestion();" id="nextQuestionBtn">
<p>›</p>
</div>
</div>
</div>
<div class="text-center">
<strong> <p>Question: {{survey.surveyQuestions[survey.scope.index].questionNum}} of {{survey.surveyQuestions.length}}</p> </strong>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<!-- <nav aria-label="Survey navigation">
<ul class="pagination pagination-sm justify-content-center">
<div ng-repeat="question in survey.surveyQuestions" >
<li class="page-item">
<a class="page-link" id = "navBtn_$index" ng-click="survey.index = $index">{{question.id}}</a>
</li>
</div>
</ul>
</nav> -->
</div>
</div>
I would like for the controller to change the variable and the view to update accordingly
Thank you for your time and thank you in advance.
It's 'survey.scope.index' not 'survey.index' in your HTML. I think you may be unclear the difference between using 'this' and '$scope'. You're mixing the two together which is not necessary. I would suggest removing 'scope' and just reference it in your HTML as 'survey.index'.

weird behavior of ngrepeat in angularJS

I am having issue with ng-repeat , its replacing all values with latest one.
E.g. I am adding a value to textbox then adding that value in ng-repeat div but its replacing all values with last value entered.
Here is Jsfiddle
https://jsfiddle.net/mahajan344/9bz4Lwxa/656/
This is happening because you have only one statusObj and you are modifying it every time someone clicks the Add New Status button. Delete the statusObj you have now, and have the AddNewStatus method create a new one each time:
var xyzApi = xyzApi || {
sayHello: function() {
return "hey there\n";
}
};
angular.module('demoApp', [])
.controller('MainController', MainController)
.provider('xyzApi', function XyzApiProvider() {
this.$get = function() {
var xyzApiFactory = {
otherFunction: function() {
//$log.log('other function called');
return 'other function \n';
}
};
//console.log(xyzApiFactory, xyzApi);
angular.merge(xyzApiFactory, xyzApi);
return xyzApiFactory;
};
});
function MainController(xyzApi) {
var vm = this;
vm.test = '';
vm.listOfStatus = [];
vm.showStatusError = false;
vm.statusText = "";
vm.sayHello = function() {
vm.test += xyzApi.sayHello() + xyzApi.otherFunction();
}
vm.AddNewStatus = function(statusText) {
if (statusText.length < 1) {
vm.showStatusError = true;
return;
} else {
vm.showStatusError = false;
}
var statusObj = {
StatusComment: statusText,
scId: 0,
scTimeStamp: new Date(),
JobNum: 0,
IsNew: 0,
};
vm.listOfStatus.push(statusObj);
vm.statusText = "";
};
vm.RemoveStatus = function(index) {
vm.listOfStatus.splice(index, 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
<pre>{{mainCtrl.test}}</pre>
<button ng-click="mainCtrl.sayHello()">
say hello!!
</button>
<div id="DivStatus">
<div class="form-group">
Status
<div class="col-md-3 col-sm-3 col-xs-12">
<input type="text" ng-model="mainCtrl.statusText" id="txtStatus" class="form-control col-md-7 col-xs-12">
<div class="text-danger error-message" id="txtStatusError" ng-show="showStatusError">Please enter new status</div>
</div>
<div class="col-md-3 col-md-3x col-sm-3 col-xs-12">
<input type="button" class="btn" ng-click="mainCtrl.AddNewStatus(mainCtrl.statusText)" value="Add New Status" />
</div>
</div>
<div class="form-group" ng-repeat="statusObj in mainCtrl.listOfStatus track by $index">
<div class="col-md-3 col-sm-3 col-xs-12">
<input type="text" value="{{statusObj.StatusComment}}" ng-disabled="true" class="form-control col-md-7 col-xs-12">
</div>
<span class="remove-record" ng-click="mainCtrl.RemoveStatus($index)" style="cursor:pointer"><i class="fa fa-times"></i></span>
</div>
</div>
</div>

How to popup chat window using node.js

I am working on node.js and began to create a chat application I have built it successfully but the problem is that I want the chat window should be open when the client click on the name of the sender(who sent the message to the client).
I will show you the example what I have done till now.
Here you can see that the chat box is already open but I want it should open when a user is selected from "List of users" and the content of chat box should be replaced whenever a new user is selected and previous content should be removed.
Here is my index.html code :
<div class="col-md-4 user-list">
<h2>List of Users</h2>
<ul class="list-group">
<li class="list-group-item"
ng-repeat="user in userList"
ng-class="{ 'active' : user.id == selectedUser.uid}"
ng-click = seletedUser(user.id,user.userName);
ng-style="{
'cursor': user.id === socketId ? 'not-allowed' :'pointer'
}"
>
<span id='{{user.id}}' >{{ user.id === socketId ? 'You': user.userName }}</span>
<span id='{{user.id + "notify"}}' style="color:black; opacity:0.5; font:2px; padding:5px; visibility:hidden;"> {{'typing...'}}</span>
</li>
</ul>
</div>
</div>
<div class="container" id="messages">
<div class="row">
<div class="col-md-8">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span> {{'Chat -' + selectedUser.uname}}
</div>
<div class="panel-body">
<ul class="chat col-md-7"
ng-repeat = "message in messages"
ng-style ="{'float':message.fromid == socketId ? 'left' : 'right'}">
<li>
<div class="clearfix">
<div class="direct-chat-text"
ng-style = "{'background-color': message.fromid == socketId ? '#d9edf7' : '#62f3bc'}"
>
{{message.msg}}
</div>
</div>
</li>
</ul>
<br></br>
</div>
<div class="panel-footer">
<div class="input-group">
<textarea elastic type="text" class="form-control custom-control" ng-model='message' ng-keyup="keyup()" ng-keydown="keydown()" ng-change="change()" placeholder="Type your message here..."></textarea>
<span class="input-group-addon btn btn-primary" ng-click="sendMsg()"><i class="glyphicon glyphicon-send"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
If you would require any other information related to code please comment.
As I am newbie to node.js so help me to solve my problem.
UPDATE
My script.js code which have sufficient details:
app.controller('app', ($scope,$timeout,socket) => {
$scope.socketId = null;
$scope.selectedUser ={ uid: null, uname: null};
$scope.messages = [];
$scope.msgData = null;
$scope.userList = [];
var TypeTimer;
var TypingInterval = 1000;
$scope.username = window.prompt('Enter Your Name');
if ($scope.username === '') {
window.location.reload();
}
$scope.seletedUser = (id,name) => {
if(id === $scope.socketId)
{
alert("Can't message to yourself.")
}
else
{
$scope.selectedUser =
{
uid: id,
uname: name
}
}
};
$scope.sendMsg = () => {
// const keyCode = $event.which || $event.keyCode;
if ($scope.message !== null && $scope.message !== '' && $scope.selectedUser.uid !== null) {
socket.emit('getMsg',{
toid : $scope.selectedUser.uid,
fromid: $scope.socketId,
msg : $scope.message,
name : $scope.username
});
$timeout.cancel(TypeTimer);
TypeTimer=$timeout( function(){
socket.emit('getTypingNotify',{
toid : $scope.selectedUser.uid,
fromid: $scope.socketId,
msg:"hidden"
});
});
$scope.message = null;
console.log($scope.selectedUser.uid);
}
else
{
alert("enter a message or select a User to send message");
}
};
socket.emit('username',$scope.username);
socket.on('userList', (userList,socketId) => {
if($scope.socketId === null){
$scope.socketId = socketId;
}
$scope.userList = userList;
});
socket.on('exit', (userList) => {
$scope.userList = userList;
});
socket.on('setMsg',(data) => {
document.getElementById(data.fromid+'notify').style.visibility= data.msg;
});
socket.on('sendMsg', (data) => {
//console.log('send');
$scope.messages.push(data);
});
my understanding is u want to show a pop up on click of a button or some text box u can use angular bootstarp model as shown here
"https://plnkr.co/edit/?p=preview"
and control the close and open in angularjs contoller and send the chat details too server side
After searching some tutorials and questions(on StackOverflow) I found a way and going to share with you all.
I created a directory name "open" and an attribute visible of this "open" directive to show and hide the dialog.
app.directive('open',function() {
return {
restrict: 'E',
template: `<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>{{"Chat -" + selectedUser.uname}}
</div>
<div class="panel-body">
<div ppp-chat></div>
<br></br>
</div>
<div class="panel-footer">
<div class="input-group">
<textarea msd-elastic type="text" class="form-control custom-control" ng-model="message" ng-keyup="keyup()" ng-keydown="keydown()" ng-change="change()" placeholder="Type your message here..."></textarea>
<span class="input-group-addon btn btn-primary" ng-click="sendMsg()"><i class="glyphicon glyphicon-send"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>`,
replace:true,
scope:false,
link: function postLink(scope,element,attrs) {
scope.$watch(attrs.visible,function(value){
if(value == true)
{
$(element).show();
}
else
$(element).hide();
});
$(element).on('show.bs.open',function() {
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.open',function() {
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
And a method in controller to toggle the chat window(hide or show)
$scope.toggleChat = () => {
$scope.showChat = false;
$scope.showChat = !$scope.showChat;
};
this toggleChat is used to change the value of showChat scope variable that is used to turn on(off) the visibility of chat box by alterating the showChat value as true or false.
In html I have replaced my id="messages" element( with its child and subchild) with
<open visible="showChat">
</open>

Angular JS: update controller when data change in second controller

what i m doing:
simple html file shows first page , in this page i have one title and button, initially i set $scope.index = 0. so, we set first position of array. when we click on next button it finds firstCtrl and first.html page. in this controller i update $scope.index by 1. so, my question is when i update $scope.index of myCtrl then $scope.index is changed on another controller i wants to change myCtrl. is it possible ? if it is then help me.
index.html:
<body ng-controller="myCtrl">
<div id="navbar">
<div class="setToggle">
<input id="slide-sidebar" type="checkbox" role="button" />
<label for="slide-sidebar"><span class="glyphicon glyphicon-menu-hamburger"></span></label>
</div>
<div class="setQuestion">
<h2>{{surveys[index].questionTitle}}</h2>
</div>
</div>
<div class="content-wrapper" class="container-fluid">
<div class="sidebar-left">
<div class="first">
<ul ng-repeat="cat in surveys[index].category" class="list-unstyled" ng-hide="checkSubCategoryValueIsNull.length">
<li class="category">
<a ng-click="expand=!expand">
<span class="glyphicon" ng-class="{'glyphicon-plus': !expand, 'glyphicon-minus': expand}">
{{cat.categoryName}}
</span>
</a>
</li>
<ul ng-repeat="subcategory in cat.categoryItemDto" class="list-unstyled">
<li ng-show="expand">
<label class="label-style-change">
<input type="checkbox" ng-click="toggleSelectionCheckbox(surveys[index], subcategory)" ng-model="subcategory.selectValue" ng-disabled="disableCheckbox">
<span class="subcategory-item" ng-disabled="disableCheckbox">{{subcategory.subCategoryName}}</span>
</label>
</li>
</ul>
</ul>
</div>
<div class="second">
<input type="button" name="Submit" value="Submit" ng-click="submitSelection()" ng-hide="hideSubmitButton" ng-disabled="!selections[index].length">
<input type="button" name="Edit" value="Edit" ng-click="EditSelection()" ng-show="hideEditButton">
</div>
</div>
<div class="portfolio">
<div id="main">
<div ng-view></div>
</div>
</div>
</div>
</body>
controller.js
(function() {
var app = angular.module("app.controllers", ["app.service"]);
app.controller("myCtrl", ["$scope", "$http", "$location", "$timeout", "surveyService", "Data",
function ($scope, $http, $location, $timeout, surveyService, Data) {
surveyService.getData(function(dataResponse) {
$scope.surveys = dataResponse;
$scope.selections = [];
/* create 2d array mannually */
var numInternalArrays = $scope.surveys.length;
for (var i = 0; i < numInternalArrays; i++) {
$scope.selections[i] = [];
};
$scope.index = 0;
var toggleCheckboxFlag = 0;
/* PRIVATE FUNCTION
for find value from selections array and replace it
*/
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
array.splice(index, 1);
toggleCheckboxFlag = 1;
}
});
}
$scope.toggleSelectionCheckbox = function (QuestionId, value) {
toggleCheckboxFlag = 0;
if (!value) return;
findAndRemove($scope.selections[$scope.index], 'categoryId', value.subCategoryId);
if (toggleCheckboxFlag != 1) {
$scope.selections[$scope.index].push({
questionId: QuestionId.questionId,
categoryId: value.subCategoryId,
categoryName: value.subCategoryName,
storeId: 1,
comment: ""
});
}
};
$scope.submitSelection = function() {
$scope.value = $scope.selections[$scope.index];
$scope.hideSubmitButton = true;
$scope.disableCheckbox = true;
$scope.hideEditButton = true;
$location.path("/question/1");
}
});
$scope.EditSelection = function() {
$scope.hideEditButton = false;
$scope.hideSubmitButton = false;
$scope.disableCheckbox = false;
$scope.value = false;
}
$scope.$watch('index', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setIndex(newValue);
});
console.log("controller", Data.getIndex())
}]);
})();
app.js
var app = angular.module('app', ['ngRoute','app.service', 'app.controllers']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/question/1', {
templateUrl: 'views/first.html',
controller: 'sidebarCtrl'
})
.when('/question/2', {
templateUrl: 'views/second.html',
controller: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<div id="content-wrapper" ng-show="value">
<div class="col-lg-offset-1 col-lg-8 col-md-12 col-sm-12 col-xs-12">
<h2 class="subCategoryLabel"><span class="label">{{value[inc].categoryName}}</span></h2>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="inc == 0" ng-click="prev()">
<i class="glyphicon glyphicon-menu-left"></i>
</button>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<form name="myForm">
<div ng-repeat="item in surveys[index].optionCategoryItemDto" class="formStyle">
<label class="text-center">
<input type="radio" name="radio" id="{{item.itemId}}" ng-value="item.itemId" ng-model="selections[index][inc].answer" required>
{{item.itemName}}
</label>
</div>
<br/>
<br/>
</form>
</div>
<div class="col-lg-3 col-lg-offset-1 col-md-offset-1 col-md-3 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="next()">
<i class="glyphicon glyphicon-menu-right"></i>
</button>
<button class="btnNext" ng-show="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="nextQuestion()">
<i class="glyphicon glyphicon-forward"></i>
</button>
</div>
</div>
<div class="col-lg-offset-3 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-4">
<textarea type="text" id="text" class="form-control txtArea" ng-model="selections[index][inc].comment" placeholder="Write comment..."></textarea>
</div>
</div>
sidebarCtrl.js
in this controller i update $scope.index when we call nextQuestion(). here $scope.index increment by one and $watch function also get latest value of index. but myCtrl is not update. i wants to update myCtrl.
(function() {
var app = angular.module("app.controllers");
app.controller("sidebarCtrl", ['$scope', "$location", "Data", function($scope, $location, Data) {
$scope.inc = 0;
$scope.next = function() {
$scope.inc += 1;
}
$scope.prev = function() {
$scope.inc -= 1;
}
$scope.nextQuestion = function() {
$scope.index += 1;
$location.path("/question/2");
}
$scope.$watch('index', function (newValue, oldValue) {
console.log("SASAS", newValue)
if (newValue !== oldValue) Data.setIndex(newValue);
});
}]);
})();
service.js
(function() {
var app = angular.module("app.service", []);
app.service("surveyService", function($http) {
this.getData = function (callbackFunc) {
$http({
method: "GET",
data: {something: true},
contentType: 'application/json',
dataType: 'jsonp',
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-survey-details"
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
};
this.setData = function(value) {
if (confirm('Do you wanna to submit?')) {
$http.post("http://localhost:8080/TheSanshaWorld/sfcms/save-survey-result-data", value).success(function(data, status) {
window.open("../index.html","_self");
});
} else {
return false;
}
};
});
app.factory('Data', function () {
var data = {
Index: ''
};
return {
getIndex: function () {
return data.Index;
},
setIndex: function (index) {
data.Index = index;
console.log("service", data.Index)
}
};
});
})();
Because sidebarCtrl is nested within myCtrl, therefore you can reach myCtrl $scope.index from sidebarCtrl using it $scope.$parent.index,
Try it by test: add any parameter value to myCtrl $scope.name='Bob';
then log it in sidebarCtrl console.log($scope.$parent.name); you should see printed 'Bob'. Do the same with index.

AngularJS: upload file inside modal-ui-bootstrap

I have an angular modal-ui, in it I upload file. The problem is that for some reason the <input> of the file doesn't triggers the app directive. The directive returns the file name and size when the <input> being changed.
this is the result I want to get:
example
I really tried already any thing, but still for some reason I can't see in the <span> the file name.
The html file :
<form novalidate ng-submit="add(Form.$valid)" name="Form">
<div class="modal-header col-lg-12">
<h3 class="col-lg-4 col-lg-offset-4">add file</h3>
</div>
<div class="modal-body">
<div class="panel-body">
<div class="row">
<div class="form-group col-lg-8" ng-class="{'has-error': notPass && Form.fileName.$invalid}">
<label class="control-label label-add-card" for="fileName">name</label>
<input class="input-add-card form-control " id="fileName" name="fileName" type="text" ng-model="fileName" ng-pattern="/^[a-z1-9]{10,}$/" ng-required="true">
<p ng-show="notPass && Form.fileName.$invalid" class="help-block">not good</p>
</div>
</div>
<div class="row">
<div class="form-group col-lg-8" ng-class="{'has-error':notPass && Form.fileExplain.$invalid}">
<label class="control-label label-add-card" for="fileExplain">explain</label>
<textarea class="input-big form-control " id="fileExplain" name="fileExplain" type="text" ng-model="fileExplain" ng-pattern="/^[a-z1-9]{1,}$/" ng-required="true"></textarea>
<p ng-show="notPass && Form.fileExplain.$invalid" class="help-block">not good</p>
</div>
</div>
<div>
<div class="form-group col-lg-12" ng-class="{'has-error':notPass && Form.uploadDownloads.$invalid}">
<input ng-model="uploadDownloads" type="file" fd-input file-name="fileName" />
<input class="btn btn-primary" type="button" value="choose" onclick="$(this).parent().find('input[type=file]').click();"/> <!-- on button click fire the file click event -->
<span class="badge badge-important">{{fileName}}</span>
<p ng-show="notPass && Form.uploadDownloads.$invalid" class="help-block">please choose</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success col-lg-12 btn-modal-costume">add</button>
</div>
</form>
the modal controller:
/**
* Created by Ariel on 22/11/2015.
*/
app.controller('uploadDownloadsController',function($scope,$modalInstance ){
app.directive('fdInput', fdInput);
function fdInput() {
return {
scope: {
fileName: '='
},
link: function(scope, element, attrs) {
element.on('change', function(evt) {
var files = evt.target.files;
console.log(files[0].name);
console.log(files[0].size);
scope.fileName = files[0].name;
scope.$apply();
});
}
}
};
$scope.fileName = '';
$scope.add = function(valid){
if(valid){
$scope.data = 'none';
var f = document.getElementById('uploadDownloads').files[0];
var r = new FileReader();
r.onloadend = function(e){
$scope.data = e.target.result;
$scope.notPass = false;
$modalInstance.close({
'data':$scope.data,
'fileName':$scope.fileName,
'fileExplain':$scope.fileExplain
});
};
/*activate the onloadend to catch the file*/
r.readAsBinaryString(f);
} else {
$scope.notPass = true;
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
here is how I have done it :
the html :
<form novalidate ng-submit="add(Form.$valid)" name="Form">
.
.
.
<div>
<div class="form-group col-lg-12" ng-class="{'has-error':notPass && Form.uploadDownloads.$invalid}">
<input ng-model="uploadDownloads" class="form-control-file" id="uploadDownloads" type="file" fd-input file-names="fileNames" />
<input class="btn btn-primary" type="button" value="choose" ng-click="choose()"/> <!-- on button click fire the file click event -->
<span class="badge badge-important">{{fileNames}}</span>
<p ng-show="notPass && Form.uploadDownloads.$invalid" class="help-block">you have to choose file</p>
</div>
</div>
.
.
.
</form>
I built a direcvtive to show thee file name dorring the upload:
/*get and shows the file name*/
app.directive('fdInput', function($timeout){
return {
scope: {
fileNames: '='
},
link:function(scope, element, attrs) {
$timeout(element.on('change', function(evt) {
var files = evt.target.files;
scope.fileNames = files[0].name;
scope.$apply();
}),0);
}
}
});
and this is the upload file controller:
app.controller('uploadDownloadsController',function($scope,$modalInstance,$timeout){
$scope.fileNames = '';
$scope.choose = function(){
$('#uploadDownloads').trigger('click');
};
$scope.add = function(valid){
if(valid){
$scope.data = 'none';
$scope.notPass = false;
/*this catches the file*/
var fileInput = document.getElementById('uploadDownloads');
var file = fileInput.files[0];
/* to send the file and the other inputs about it, need to use formData type*/
var formData = new FormData();
formData.append('file', file);
formData.append('fileName', $scope.fileName);
formData.append('fileExplain', $scope.fileExplain);
console.log(formData);
$modalInstance.close(formData);
} else {
$scope.notPass = true;
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});

Resources