Angular ui-calendar auto refresh on form submission - angularjs

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/

Related

ion-slides, each overlap with ng-repeat

I'm real newbie in ionic, html, angular and java script. I have an app that take some JSON data and display it with ng-repeat.
But when I tried to switch to the next slide, it overlap. and I have an $interval that refresh JSON each 5 sec, it reset to the first slide also.
here html:
<ion-view title="home">
<ion-content ng-controller="temperatureCtrl">
<div ng-init="init()"></div>
<ion-slides options="options" slider="data.slider" >
<ion-slide-page ng-repeat="channel in channels">
<div class="list">
<h2><center>canal# {{channel.canal}}</center></h2>
<br/>
<center>
<button class="button button-stable" ng-click="switchChannel(channel, channel.canal)" ng-model="channel.status">
{{channel.status}}
</button>
</center>
<div class="list">
<label class="item item-input">
<input type="text" style="text-align:center;" placeholder="Channel name" ng-model="channel.name" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
</label>
</div>
<h4><center>
<span class="Ainput" ><h3>{{channel.temperature}}ºC</h3></span>
</center></h4>
<h3><center>Setpoint= {{channel.setPoint}}</center></h3><br>
<div class="item range range-positive">
<i class="icon ion-minus-round"></i>
<input type="range" name="setpoint" min="5" max="30" step="0.5" value="33" ng-model="channel.setPoint" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
<i class="icon ion-plus-round"></i>
</div>
<centrer>
<button class="button button-dark button-block padding " ng-click="channelsClk(channel, channel.setPoint)">ok</button>
</centrer>
<h3>
<span class="permRun">{{channel.permission}}</span>
</h3>
<h3>
<span class="AoutputChannel">{{channel.percentOut}}%</span>
</h3>
</ion-slide-page>
</ion-slides>
</ion-content>
and the controler:
main.controller("temperatureCtrl", ["$scope", "$interval", "ArduinoService", function($scope, $interval, service) {
var autoRefresh;
$scope.channels = [];
$scope.options = {
loop: false,
effect: 'fade',
speed: 500,
}
$scope.data = {};
$scope.$watch('data.slider', function(nv, ov) {
$scope.slider = $scope.data.slider;
})
function startRefresh(){
autoRefresh = $interval(function() {
updateAjax();
}, 5000);
}
function updateAjax() {
service.getChannels(function(err, result) {//get json data
if (err) {
return alert(err);
}
// puis les mets dans le scope
$scope.channels = result.channels;
})
};
$scope.init = function() { //on load page first get data
updateAjax();
startRefresh()
}
$scope.switchChannel = function($scope, channel) { // change name function
var switchCh = {canal : $scope.canal, status : $scope.status}
service.switchChannel(switchCh, function() {
});
updateAjax();
};
$scope.channelsClk = function($scope, channel) {
var chanObj = {setPoint : $scope.setPoint, name : $scope.name, canal : $scope.canal
};
service.putChannels(chanObj, function() {
});
}
$scope.stopRefresh = function() { //ng-mousedown
$interval.cancel(autoRefresh);
};
$scope.restartRefresh = function() {
startRefresh();
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopRefresh();
});
}]);
remove option fade solve the problem.
$scope.options = {
loop: false,
//effect: 'fade', /* <-- */
speed: 500,
}

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.

Data not passing to spring controller from service.js using 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);
});
}
}
});

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.

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Resources