Data not passing to spring controller from service.js using angularjs - angularjs

I’m unable to send the ownerName name and ownerTeam name from service.js to Spring controller.When I tying to send multiple ownerName and ownerTeam only the last updated value is passed. Please help me on this.
CreateTask.html:
<fieldset>
<legend>Owners</legend>
<div class="form-group" ng-repeat="owner in formData.owners">
<div class="col-md-2 " ><label for="ownerName" translate="task.form.ownerName">Name</label></div>
<div class="col-md-3 "><input type="text" class="form-control" id="owner.ownerName" placeholder="{{'task.form.ownerName.placeholder' | translate}}" ng-model="owner.ownerName"></div>
<div class="col-sm-1 "><img src="images/searchicon.png" width="23" height="23"/></div>
<div class="col-md-2"><label for="ownerTeamName" translate="task.form.ownerTeamName">Team</label></div>
<div class="col-md-3">
<select class="form-control" id="owner.ownerTeamName" placeholder="{{'task.form.ownerTeamName.placeholder' | translate}}" ng-model="owner.ownerTeamName" ng-options="opt as opt for opt in teamNames" ng-init="owner.ownerTeamName='Release Management'"">
</select>
</div>
<div class="col-sm-1 col-centered col-fixed"> <img src="images/plus.png" width="15" height="15" ng-click="addOwners()"/></div>
<br/><br/>
</div>
</fieldset>
Controller.js
$scope.owners=[{ownerName:"",ownerTeamName:""}];
$scope.formData = {owners: [{ownerName:"",ownerTeamName:""}] };
$scope.addOwners = function(){
/*$scope.formData.owners.push({ownerName: $scope.formData.owners[0].ownerName, ownerTeamName: $scope.formData.owners[0].ownerTeamName });*/
$scope.formData.owners.push({ownerName:'',ownerTeamName:''});
TaskCreationService.createNewTask({
"owners":$scope.formData.owners
};
Service.js
releaseApp.factory('TaskCreationService', function ($rootScope, $http) {
var owners=[];
var ownerName=[];
var ownerTeamName =[];
return {
createNewTask: function (param) {
var ownerList = param.owners;
for(var i = 0; i < ownerList.length; i++){
ownerName=ownerList[i].ownerName;
ownerTeamName = ownerList[i].ownerTeamName;
}
var data ={
"owners":[{
"ownerName":{
"name":ownerName
},
"ownerTeam":{
"name":ownerTeamName
}
}]
}
$http.post('taskCreation/createNewTask', data).success(function (data, status) {
console.log('success');
alert('Task Created Successfully');
}).error(function(data, status) {
console.log((data || 'No task created') + ': ' + status);
});
}
}
});

Related

how can update my form in modal in angular js?

hello i am creating mean application in which i want to update record.the record is in table format and when user click on edit button then a modal appears with its database values on input text box . I have not any problem in updating field but i stuck in updating video part. How can I do it??
html form (i use single form for creating and updating)
<div class="panel panel-default">
<div class="panel-heading">Add Videos</div>
<div class="panel-body">
<div style="margin:10px;">
<form name="addVideos" class="" method="post">
<div class="alert alert-success" ng-show="success" style="background-color:black;">
<strong>successfully updated!!</strong> Redirecting to all videos page.
</div>
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" ng-model="form.title" required name="title" placeholder="Enter Title">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" ng-model="form.description" required name="description" rows="5" id="comment" placeholder="Enter Description"></textarea>
</div>
<div class="form-group">
<label>Author</label>
<input type="text" class="form-control" required ng-model="form.author" name="author" id="exampleInputPassword1" placeholder="Enter Author Name">
</div>
<div class="form-group">
<label>duration</label>
<input type="text" class="form-control" required ng-model="form.duration" name="duration" id="exampleInputPassword1" placeholder="Enter Author Name">
</div>
<!-- <div class="form-group">
<label>ispublic</label>
<input type="text" class="form-control" required ng-model="form.public" name="public" id="exampleInputPassword1" placeholder="Enter Author Name">
</div> -->
<div class="form-group">
<label for="sel1">ispublic:</label>
<select class="form-control" ng-model="form.public" >
<option ng-selected="test==false" value="0">0</option>
<option ng-selected="test==true" value="1">1</option>
</select>
</div>
<div class="row">
<div class="col-md-2" style="margin-top: 19px;" >
<!-- <!ng-hide="display" !> -->
<input type="file" accept="video/*" file-model="myFile" required/>
</div>
<div class="col-md-8" style="margin-left:29px;">
<button ng-click="add == true ? uploadFile(form) : updateVideo()" class="btn btn-danger" ng-disabled="addVideos.$invalid" style="margin:10px;">Submit</button>
</div>
</div>
<progress value="{{progressBar}}" max="100" ng-show="view">
</progress>
<div class="progress" ng-show="view" style="width:40%;">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="{{progressBar}}" aria-valuemin="0" aria-valuemax="100" style="width:{{progressBar}}%">
{{progressBar}}% Complete (success)
</div>
</div>
</form>
</div>
</div>
</div>
my controller
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxx.mp4'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
var localstorageApp = angular.module('BlurAdmin.pages.videos.allVideos');
localstorageApp.controller('TbleCtrl',['$rootScope','$scope', '$filter', 'editableOptions', 'editableThemes', '$window', '$http',
'$uibModal', 'baProgressModal','localStorageService','$state','$rootScope',
function ($rootScope,$scope, $filter, editableOptions, editableThemes, $window, $http, $uibModal,
baProgressModal,localStorageService,$state,$rootScope) {
var token = localStorageService.get('TOKEN')
if(token == null){
$window.location.href = '/index.html';
}
token = token.substring(1, token.length - 1);
$http.get("/api/loggedin/"+token).then(function(response) {
console.log("response"+JSON.stringify(response.data.error))
if(response.data.error == true){
localStorageService.remove('TOKEN')
$window.location.href = '/index.html';
}
});
$scope.users = [];
$scope.display=true;
// $scope.form = [];
//$scope.bool = null;
$scope.id = 0;
$scope.redirect = function () {
$window.location.href = "#/videos/addVideos";
}
$http.get("/api/all-videos").then(function(response) {
$scope.users = response.data.data;
console.log(response.data.data);
});
$scope.open = function(e,id,page, size, addOrEdit) {
$scope.updateVideo() = function(){
alert('working');
}
// $scope.bool = bool
$scope.id = id
$scope.display=true;
var modalInstance = $uibModal.open({
// animation: $ctrl.animationsEnabled,
// ariaLabelledBy: 'modal-title',
// ariaDescribedBy: 'modal-body',
templateUrl: page,
controller: 'ModalInstanceCtrl',
controllerAs: '$scope',
size: size,
// appendTo: parentElem,
resolve: {
users: function () {
return $scope.users;
},
id: function () {
return $scope.id;
}
}
});
modalInstance.result.then(function (selectedItem) {
// console.log("selectedItem"+JSON.stringify(selectedItem.data));
$scope.users = selectedItem;
// $scope.users.push(selectedItem.data)
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.removeVideo = function(id, $index) {
var m = parseInt(id);
if ($window.confirm("Are you sure you want to delete?") == true) {
$http.post("/api/delete-video/" + m).then(function(response) {
$scope.users.splice( $index, 1 );
});
// $window.location.reload()
} else {
}
}
$scope.openProgressDialog = baProgressModal.open;
// editableOptions.theme = 'bs3';
// editableThemes['bs3'].submitTpl = '<button type="submit" class="btn btn-primary btn-with-icon"><i class="ion-checkmark-round"></i></button>';
// editableThemes['bs3'].cancelTpl = '<button type="button" ng-click="$form.$cancel()" class="btn btn-default btn-with-icon"><i class="ion-close-round"></i></button>';
}
])
var qwe='';
angular.module('BlurAdmin.pages.users').directive('fileModel', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
qwe= element[0].files[0];
console.log(element[0].files[0].name);
});
});
}
};
}]).service('hexafy', ['$http', '$window','$timeout', function($http, $window,$timeout) {
this.myFunc = function (x) {
return x.toString(16);
}
// GET ALL INFORMATION IN VIDEOS
this.getAll = function(t,x){
console.log(x);
$http.get("/api/get-video/"+x).then(function(response) {
console.log(response);
// console.log(response.data.data);
console.log(response.data.response.data);
t.form = response.data.response.data;
// $scope.form.public = response.data.response.data.ispublic;
t.test = response.data.response.data.ispublic;
// console.log($scope.form.level);
// $scope.form.level = $scope.levels[response.data.response.data.level - 1];
// console.log($scope.form.level);
});
}
this.display = function(p){
console.log(p);
console.log(qwe);
}
this.updateVideo = function(){
console.log(qwe);
alert('working');
}
}]).controller('ModalInstanceCtrl', ['$scope', '$uibModalInstance', '$http', 'id', '$timeout','hexafy' ,function ($scope, $uibModalInstance,$http,id,$timeout,hexafy) {
$scope.form = {};
$scope.test = '';
// $scope.b = bool;
console.log($scope.b);
$scope.display=true;
console.log(hexafy.myFunc(187));
hexafy.getAll($scope,id);
console.log("id value "+id)
var file = $scope.myFile;
console.log(file);
}])
How could i detect file in modal??

Angular ui-calendar auto refresh on form submission

i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function(date, cell) {
var today = new Date();
today = moment(today).toDate();
var end = new Date();
end = moment(end).toDate();
end.setDate(today.getDate() + 7);
date = moment(date).toDate();
angular.forEach($scope.holidayList, function(value) {
if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
cell.css("background-color", "#2bbbad");
//$('.date').text('Today');
cell.prepend("<span style=\"max-width:200px;word-wrap:break-word;margin-top:10px;\">" + value.description + "</span>");
cell.prepend("<br>")
}
});
},
eventRender: $scope.eventRender,
}
};
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error from holidaylist");
});
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
g-include
<div id="controllerid">
<div class="row" >
<div class="col s10 m10 l10">
<div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
</div>
</div>
<!-- Modal Structure -->
<div id="modal1" class="modal" ng-controller="MyAddController">
<div class="modal-content">
<h4>Apply Leave</h4>
<div class="row">
<form class="col s12" id="form1">
<div class="row modal-form-row">
<div class="input-field col s6">
<input id="num" type="text" class="validate" ng-model="test.num"> <label for="num">num</label>
</div>
<div class="input-field col s6">
<input id="ename" type="text" class="validate" ng-model="test.title"> <label for="ename">Employee Name</label>
</div>
</div>
<div class="row">
<form class="col s12">
<div class="row modal-form-row">
<div class="input-field col s5">
<input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly >
</div>
<div class="input-field col s5">
<input id="endDate" type="text" class="validate" value="{{selectionDate.endDate | date}}" readonly>
</div>
<div class="input-field col s1">
<p>
<input type="checkbox" id="test6" ng-model="test.isHalfDay" /> <label for="test6">Half Day</label>
</p>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="description" type="text" class="validate" ng-model="test.description"> <label for="description">Description</label>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</button>
</div>
</div>
and my add controller
app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
$scope.test = {};
$scope.add = function() {
$("#modal1").closeModal();
$scope.test1=$rootScope.selectionDate;
var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
console.log(""+jsonData);
$http({
url: "rest/leave/create",
method: "POST",
data: jsonData,
headers: {'Content-Type': 'application/json'}
}).success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
}).error(function(data, status, headers, config) {
alert("error from create leave");
})
}
});
ANy help would be appreciated
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.
Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:
.success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
//add the event to the calendar UI without refreshing the events
$('[ui-calendar]').fullCalendar("renderEvent",
{
start: jsonData.startDate,
end: jsonData.endDate,
title: jsonData.title
},
true //make it stick even when the view changes
);
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.
The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/

AngularJS: model is not binding

I am using Angular Modal and when I send the input to the modal and set the scope variable, I cannot see the binding happening.
Here is the code:
Note: I am yet to implement the close function in the controller for the modal.
Code for showing the modal:
$scope.approveReq = function (id) {
ModalService.showModal({
templateUrl: "/app/mis/jobno/createjno.html",
controller: "CreateJnoCtrl",
inputs: { input: id }
}).then(function (modal) {
// The modal object has the element built, if this is a bootstrap modal
// you can call 'modal' to show it, if it's a custom modal just show or hide
// it as you need to.
modal.element.modal();
modal.close.then(function (result) {
$scope.message = result ? "You said Yes" : "You said No";
});
});
};
HTML of the modal
<div id="jobcreate" class="modal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<form name="jobcreate">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create a new Job</h4>
</div>
<div class="modal-body">
<fieldset class="form-group row">
<label for="iBranchId" class="col-sm-2 form-control-label">Branch</label>
<div class="col-sm-4">
<select class="form-control" ng-required="true" ng-model="jobno.BranchId" id="iBranchId">
<option ng-repeat="b in branches" value="{{b.org_id}}">{{b.org_location}}</option>
</select>
</div>
<label for="iJobType" class="col-sm-2 form-control-label">Job Type</label>
<div class="col-sm-4">
<select class="form-control" style="width:250px" ng-required="true" ng-model="jobno.iJobType" id="iJobType">
<option ng-repeat="jt in jobTypes" value="{{jt.iJobTypeId}}">{{jt.vJobType}}</option>
</select>
</div>
</fieldset>
<fieldset class="form-group row">
<label for="ClieintId" class="col-sm-2 form-control-label">Customer</label>
<div class="col-sm-4">
<select class="form-control" id="ClieintId" ng-required="true" ng-model="selClient" ng-change="getlocs()">
<option ng-repeat="c in clientList" value="{{c.Id}}">{{c.Name}}</option>
</select>
</div>
<label for="vClientLoc" class="col-sm-2 form-control-label">Location</label>
<div class="col-sm-4">
<select class="form-control" id="vClientLoc" ng-required="true" ng-model="jobno.vClientLoc">
<option ng-repeat="l in clientLocs" value="{{l.Loc_Id}}">{{l.Loc_Name}}</option>
</select>
</div>
</fieldset>
<fieldset class="form-group row">
<label for="ContractId" class="col-sm-2 form-control-label">Contract No</label>
<div class="col-sm-4">
<select class="form-control" ng-required="true" ng-model="jobno.ContractId" id="ContractId" ng-options="c.Contract_Id as (c.Contract_No) for c in contracts"></select>
</div>
<div class="col-sm-6" ng-show="createdJobNo">{{createdJobNo}} Created!</div>
</fieldset>
</div>
<div class="modal-footer">
<div class="btn-group">
<button type="button" id="createJobNo" ng-if="!jobcreate.$pristine" ng-disabled="jobcreate.$invalid" class="btn btn-success" ng-click="createJobNo()">Create Job Number</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
Controller for the modal
angular.module('trg-app.mis').controller('CreateJnoCtrl', ['$http', '$scope', 'ClientDataService', 'input', 'close', function ($http, $scope, ClientDataService, input, close) {
//create Job No
//Get input if any
$scope.jobReq;
//Empty Job
$scope.jobno = {
iJobType: null,
vClientLoc: null,
vJobNo: null,
iRefJobNo: 0,
vRemark: null,
ContractId: 1,
UpdatedBy: 1,
BranchId: null
};
if (input != undefined) {
$scope.jobReq = input;
console.log("Input Received for JobReq: ", input);
$scope.jobno = {
iJobType: $scope.jobReq.Job_Type,
vClientLoc: $scope.jobReq.Client_Location,
vJobNo: null,
iRefJobNo: 0,
vRemark: null,
ContractId: 1,
UpdatedBy: 1,
BranchId: $scope.jobReq.Org_Location
};
}
else {
$scope.jobno = {
iJobType: null,
vClientLoc: null,
vJobNo: null,
iRefJobNo: 0,
vRemark: null,
ContractId: 1,
UpdatedBy: 1,
BranchId: null
};
}
$scope.branches;
$scope.getBranches = function () {
$http.get("/api/orgdetails/").then(
function (resp) {
console.log(resp);
$scope.branches = resp.data;
},
function (err) {
console.log("Error: ", err);
}
);
};
$scope.getBranches();
$scope.jobTypes = {};
$scope.getJobTypes = function () {
console.log("getting Job Types");
$http.get('/api/jobtypes/').then(
function (resp) {
console.log('Response: ', resp);
$scope.jobTypes = resp.data;
},
function (err) {
console.log("Error: ", err);
}
);
};
$scope.getJobTypes();
$scope.clientList;
//get minimal client list and bind to the side bar
$scope.getClients = function () {
ClientDataService.GetClientList()
.then(function (response) {
$scope.clientList = response;
});
};
$scope.getClients();
$scope.clientLocs;
$scope.selClient;
//locs should be brought in when we go to the location editing
$scope.getlocs = function () {
console.log("$scope.selClient: ", $scope.selClient)
if ($scope.selClient != undefined) {
ClientDataService.GetClientLocs($scope.selClient)
.then(function (response) {
$scope.clientLocs = response;
});
$scope.getContracts($scope.selClient);
}
};
//$scope.getlocs();
$scope.contracts;
$scope.getContracts = function (ClientId) {
$http.get('/api/Contracts/client/' + ClientId).then(
function (response) {
$scope.contracts = response.data;
},
function (error) {
console.log("Error getting contracts: ", error);
}
);
};
$scope.createdJobNo;
$scope.createJobNo = function () {
if ($scope.jobno) {
$scope.createdJobNo = null;
console.log($scope.jobno);
$http.post('/api/jobnos/', $scope.jobno).then(
function (response) {
console.log("Job Created: ", response.data.vJobNo);
//$scope.jobno.vJobNo = response.data.vJobNo;
$scope.createdJobNo = response.data.vJobNo;
//TODO: if Job is created from Req, update additional info
//$scope.initJCreate();
},
function (error) {
console.log("Error!");
}
);
}
};
}]);

angularjs with ng-repeat. cant access the data in controler when i use ng-repeat

I use the following ng-model with ng-repeat and I tried to access the data in my controller but it seems that the data cant be accessed there.
<div ng-controller="myCtrl" class="container">
<fieldset data-ng-repeat="contact in choices">
<input class="form-control" ng-model='contact.firstname'>
<input class="form-control" ng-model='contact.lastname'>
<input class="form-control" ng-model='contact.email'>
<input class="form-control" ng-model='contact.contact'>
<input class="form-control" ng-model='contact.adress'>
<input class="form-control" ng-model='contact.city'>
<input class="form-control" ng-model='contact.state'>
<button class="btn btn-primary" ng-click="addcontact()">Add</button></td>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
</div>
</div>
And use the following ng-app
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.choices = [{
id: 'choice1'
}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id': 'choice' + newItemNo
});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length - 1;
$scope.choices.splice(lastItem);
};
var refresh = function() {
$http.get('/contactlist').success(function(response) {
console.log("in m new controler now");
$scope.contactlist = response;
$scope.contact = "";
});
};
refresh();
$scope.addcontact = function() {
console.log($scope.contact);
$http.post('/contactlist', $scope.contact).success(function(response)
{
console.log(response);
refresh();
});
};
});
I can't access the data in $scope for the dynamically added controls through ng-repeat
In order to acess the data you should use
$scope.choices[index]
Index is the number of index you want to acces

Image uploading/cropping functionality is not working in tabset in angularjs

I am new to angularjs.
I want to implement https://angular-file-upload.appspot.com/ image upload functionality in tabs. When I put html elements which are required for image upload inside
<tabset><tab></tab></tabset> it doesn't work, but when I put it outside tabset it worked fine, but I want it inside <tabset><tab></tab></tabset>.
I am getting this error when I put html code inside <tabset></tabset>
Error: document.getElementById(...) is null
handleDynamicEditingOfScriptsAndHtml#http://localhost/angularAdmin/js/controllers/userForm.js:190:34
#http://localhost/angularAdmin/js/controllers/userForm.js:189:1
invoke#http://localhost/angularAdmin/vendor/angular/angular.js:4118:14
$ControllerProvider/this.$get</</<#http://localhost/angularAdmin/vendor/angular/angular.js:8356:11
nodeLinkFn/<#http://localhost/angularAdmin/vendor/angular/angular.js:7608:13
forEach#http://localhost/angularAdmin/vendor/angular/angular.js:347:11
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7607:11
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/</<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3762:11
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://localhost/angularAdmin/vendor/angular/angular.js:14518:15
transitionTo/$state.transition<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3169:11
processQueue#http://localhost/angularAdmin/vendor/angular/angular.js:12984:27
scheduleProcessQueue/<#http://localhost/angularAdmin/vendor/angular/angular.js:13000:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost/angularAdmin/vendor/angular/angular.js:14200:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost/angularAdmin/vendor/angular/angular.js:14016:15
$RootScopeProvider/this.$get</Scope.prototype.$evalAsync/<#http://localhost/angularAdmin/vendor/angular/angular.js:14238:15
completeOutstandingRequest#http://localhost/angularAdmin/vendor/angular/angular.js:4842:7
Browser/self.defer/timeoutId<#http://localhost/angularAdmin/vendor/angular/angular.js:5215:7
<div ui-view="" class="fade-in ng-scope">
[1]: https://angular-file-upload.appspot.com/
app.js
'use strict';
angular.module('app', [
'ngFileUpload',
'toaster',
'LocalStorageModule',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router',
'ui.bootstrap',
'ui.load',
'ui.jq',
'ui.validate',
'oc.lazyLoad',
'pascalprecht.translate'
]);
Controller
'use strict';
/* Controllers */
var version = '3.0.6';
// Form controller
app.controller('FormProfileCtrl', ['$scope', '$http', '$timeout', '$compile', '$upload', function ($scope, $http, $timeout, $compile, $upload) {
$scope.usingFlash = FileAPI && FileAPI.upload != null;
$scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);
$scope.changeAngularVersion = function () {
window.location.hash = $scope.angularVersion;
window.location.reload(true);
};
$scope.angularVersion = window.location.hash.length > 1 ? (window.location.hash.indexOf('/') === 1 ?
window.location.hash.substring(2) : window.location.hash.substring(1)) : '1.2.20';
$scope.$watch('files', function (files) {
console.log(files);
$scope.formUpload = false;
if (files != null) {
for (var i = 0; i < files.length; i++) {
$scope.errorMsg = null;
(function (file) {
generateThumbAndUpload(file);
})(files[i]);
}
}
});
$scope.uploadPic = function (files) {
$scope.formUpload = true;
if (files != null) {
generateThumbAndUpload(files[0])
}
}
function generateThumbAndUpload(file) {
$scope.errorMsg = null;
$scope.generateThumb(file);
if ($scope.howToSend == 1) {
uploadUsing$upload(file);
} else if ($scope.howToSend == 2) {
uploadUsing$http(file);
} else {
uploadS3(file);
}
}
$scope.generateThumb = function (file) {
if (file != null) {
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
file.dataUrl = e.target.result;
});
}
});
}
}
}
function uploadUsing$upload(file) {
file.upload = $upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'my-header': 'my-header-value'
},
fields: {username: $scope.username},
file: file,
fileFormDataName: 'myFile',
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
file.upload.xhr(function (xhr) {
// xhr.upload.addEventListener('abort', function(){console.log('abort complete')}, false);
});
}
function uploadUsing$http(file) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
$timeout(function () {
file.upload = $upload.http({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: e.target.result
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}, 5000);
}
fileReader.readAsArrayBuffer(file);
}
function uploadS3(file) {
file.upload = $upload
.upload({
url: $scope.s3url,
method: 'POST',
fields: {
key: file.name,
AWSAccessKeyId: $scope.AWSAccessKeyId,
acl: $scope.acl,
policy: $scope.policy,
signature: $scope.signature,
"Content-Type": file.type === null || file.type === '' ? 'application/octet-stream' : file.type,
filename: file.name
},
file: file,
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
storeS3UploadConfigInLocalStore();
}
$scope.generateSignature = function () {
$http.post('/s3sign?aws-secret-key=' + encodeURIComponent($scope.AWSSecretKey), $scope.jsonPolicy).
success(function (data) {
$scope.policy = data.policy;
$scope.signature = data.signature;
});
}
if (localStorage) {
$scope.s3url = localStorage.getItem("s3url");
$scope.AWSAccessKeyId = localStorage.getItem("AWSAccessKeyId");
$scope.acl = localStorage.getItem("acl");
$scope.success_action_redirect = localStorage.getItem("success_action_redirect");
$scope.policy = localStorage.getItem("policy");
$scope.signature = localStorage.getItem("signature");
}
$scope.success_action_redirect = $scope.success_action_redirect || window.location.protocol + "//" + window.location.host;
$scope.jsonPolicy = $scope.jsonPolicy || '{\n "expiration": "2020-01-01T00:00:00Z",\n "conditions": [\n {"bucket": "angular-file-upload"},\n ["starts-with", "$key", ""],\n {"acl": "private"},\n ["starts-with", "$Content-Type", ""],\n ["starts-with", "$filename", ""],\n ["content-length-range", 0, 524288000]\n ]\n}';
$scope.acl = $scope.acl || 'private';
function storeS3UploadConfigInLocalStore() {
if ($scope.howToSend == 3 && localStorage) {
localStorage.setItem("s3url", $scope.s3url);
localStorage.setItem("AWSAccessKeyId", $scope.AWSAccessKeyId);
localStorage.setItem("acl", $scope.acl);
localStorage.setItem("success_action_redirect", $scope.success_action_redirect);
localStorage.setItem("policy", $scope.policy);
localStorage.setItem("signature", $scope.signature);
}
}
(function handleDynamicEditingOfScriptsAndHtml($scope, $http) {
$scope.defaultHtml = document.getElementById('editArea').innerHTML.replace(/\t\t\t\t/g, '');
$scope.editHtml = (localStorage && localStorage.getItem("editHtml" + version)) || $scope.defaultHtml;
function htmlEdit(update) {
document.getElementById("editArea").innerHTML = $scope.editHtml;
$compile(document.getElementById("editArea"))($scope);
$scope.editHtml && localStorage && localStorage.setItem("editHtml" + version, $scope.editHtml);
if ($scope.editHtml != $scope.htmlEditor.getValue())
$scope.htmlEditor.setValue($scope.editHtml);
}
$scope.$watch("editHtml", htmlEdit);
$scope.htmlEditor = CodeMirror(document.getElementById('htmlEdit'), {
lineNumbers: true, indentUnit: 4,
mode: "htmlmixed"
});
$scope.htmlEditor.on('change', function () {
if ($scope.editHtml != $scope.htmlEditor.getValue()) {
$scope.editHtml = $scope.htmlEditor.getValue();
htmlEdit();
}
});
})($scope, $http);
$scope.confirm = function () {
return confirm('Are you sure? Your local changes will be lost.');
}
$scope.getReqParams = function () {
return $scope.generateErrorOnServer ? "?errorCode=" + $scope.serverErrorCode +
"&errorMessage=" + $scope.serverErrorMsg : "";
}
angular.element(window).bind("dragover", function (e) {
e.preventDefault();
});
angular.element(window).bind("drop", function (e) {
e.preventDefault();
});
}])
;
View
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3">Edit User</h1>
</div>
<div class="wrapper-md">
<!-- breadcrumb -->
<div>
<ul class="breadcrumb bg-white b-a">
<li><a ui-sref="app.dashboard"><i class="fa fa-home"></i> Dashboard</a></li>
<li class="active">Edit User</li>
</ul>
</div>
<!-- / breadcrumb -->
<div class="col-lg-12">
<div class="wrapper-md" ng-controller="FormProfileCtrl">
<form name="userForm" class="form-validation">
<tabset justified="true" class="tab-container">
<tab heading="Personal Information">
<div class="panel-body">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" ng-model="user.vName" >
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" ng-model="user.vEmail">
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vPhone" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vAddress" ></textarea>
</div>
<div class="form-group pull-in clearfix">
<div class="col-sm-6">
<label>Enter password</label>
<input type="password" class="form-control" name="vPassword" ng-model="vPassword" >
</div>
<div class="col-sm-6">
<label>Confirm password</label>
<input type="password" class="form-control" name="confirm_password" required ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' ">
<span ng-show='form.confirm_password.$error.validator'>Passwords do not match!</span>
</div>
</div>
</div>
</tab>
<tab heading="Company Information">
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" ng-model="user.vCompanyName" >
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vCompanyPhone" >
</div>
<div class="form-group">
<label>Designation</label>
<input type="text" class="form-control" ng-model="user.vDesignation" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vCompanyAddress" ></textarea>
</div>
</tab>
</tabset>
<!-- I want -->
<div class="upload-div">
<div class="upload-buttons">
<div id="editArea">
<fieldset><legend>Upload right away</legend>
<div ng-file-drop ng-file-select ng-model="files" ng-model-rejected="rejFiles"
drag-over-class="{accept:'dragover', reject:'dragover-err', delay:100}" class="drop-box"
ng-multiple="true" allow-dir="true" ng-accept="'image/*,application/pdf'">
Drop Images or PDFs<div>or click to select</div>
</div>
<div ng-no-file-drop class="drop-box">File Farg&Drop not supported on your browser</div>
</fieldset>
<br/>
</div>
</div>
<ul ng-show="rejFiles.length > 0" class="response">
<li class="sel-file" ng-repeat="f in rejFiles">
Rejected file: {{f.name}} - size: {{f.size}}B - type: {{f.type}}
</li>
</ul>
<ul ng-show="files.length > 0" class="response">
<li class="sel-file" ng-repeat="f in files">
<img ng-show="f.dataUrl" ng-src="{{f.dataUrl}}" class="thumb">
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%">{{f.progress}}%</div>
</span>
<button class="button" ng-click="f.upload.abort();
f.upload.aborted = true"
ng-show="f.upload != null && f.progress < 100 && !f.upload.aborted">Abort</button>
{{f.name}} - size: {{f.size}}B - type: {{f.type}}
<a ng-show="f.result" href="javascript:void(0)" ng-click="f.showDetail = !f.showDetail">details</a>
<div ng-show="f.showDetail">
<br/>
<div data-ng-show="f.result.result == null">{{f.result}}</div>
<ul>
<li ng-repeat="item in f.result.result">
<div data-ng-show="item.name">file name: {{item.name}}</div>
<div data-ng-show="item.fieldName">name: {{item.fieldName}}</div>
<div data-ng-show="item.size">size on the serve: {{item.size}}</div>
<div data-ng-show="item.value">value: {{item.value}}</div>
</li>
</ul>
<div data-ng-show="f.result.requestHeaders" class="reqh">request headers: {{f.result.requestHeaders}}</div>
</div>
</li>
</ul>
<br/>
<div class="err" ng-show="errorMsg != null">{{errorMsg}}</div>
</div>
<input type="hidden" class="form-control" ng-model="user.iUserID">
<input type="submit" class="btn btn-success" ng-click="postForm(user)">
</form>
</div>
</div>
I had a similar problem with ng-file-upload and tabset. Here is how I solved it.
In my controller, I created a new object:
$scope.tab_data = {}
and then changed the watch to
$scope.$watch 'tab_data.files', ->
$scope.upload $scope.tab_data.files
Lastly, I updated the ng-model in my html tag.
<div ngf-drop ngf-select ng-model="tab_data.files" class="drop-box" ngf-drag-over-class="dragover" ngf-multiple="true" ngf-allow-dir="true" ngf-accept="'.jpg,.png,.pdf'" class="drop-box">
<div ngf-drop-available >Drop Images here</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
<div>click to select</div>
</div>
Of course my solution is in coffeescript...sorry if that is an issue but it should be easy for you to convert back to js.

Resources