angularjs: saving multiple students at the same time - javascript

i am trying to save number of students at the time,i wrote the following code but i did not know where to go further. any more info or links to resources regarding this topic would be much appreciated
what i have done so far :
<div ng-controller="MainCtrl">
<fieldset data-ng-repeat="student in students">
<input type="text" ng-model="student.class" name="" placeholder="Class Name ">
<input type="text" ng-model="student.firstname" name="" placeholder="First Name ">
<input type="text" ng-model="student.lastname" name="" placeholder="Last Name ">
<button class="btn btn-danger" ng-show="$last" ng-click="removeStudent()">-</button>
</fieldset>
<button class="btn btn-primary" ng-click="addNewStudent()">New Student</button>
<button class="btn btn-primary" ng-click="save()">Save</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
the controller is:
app.controller('MainCtrl', function($scope, $modalInstance, $students) {
$scope.students = [];
$scope.addNewStudent = function() {
$scope.students.push({
classname: "",
firstname: "",
lastname: ""
});
};
$scope.removeStudent = function() {
var lastItem = $scope.students.length - 1;
$scope.students.splice(lastItem);
};
$scope.save = function() {
$modalInstance.close($scope.students);
};
$scope.delete = function() {
$scope.students['deleted'] = 1;
$modalInstance.close($scope.students);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
in the view i can write the infos of students but when i click save button it only save the first student
modal instance:
$scope.openStudent = function (student) {
var modalInstance = $modal.open({
templateUrl: 'modalStudent.html',
controller: 'mainCTRL',
windowClass:'app-modal-window',
resolve: {
students: function () {
var students= {};
if (student !== undefined){
students['classname'] = student.classname;
students['firstname'] = student.firstname ;
students['lastname'] = student.lastname;
students['nachname'] = student.nachname;
}
console.log("studinfo",students);
return students;
}
}
});
modalInstance.result.then(function (students) {
if (students.deleted === undefined || students.deleted == 0) {
oStudent = { classname: students.classname,
firstname: students.firstname,
lastname: students.lastname,
delete_time:"0000-00-00 00:00:00"
};
saveStudent( $indexedDB,Student).then( function(id) {
$scope.buildMenu();
});
} else {
oStudent = { id: students.id,
delete_time:new Date().toISOString()
};
deleteStudent( $indexedDB, $scope, students.id).then( function(id) {
saveStudent( $indexedDB, Student, $scope.selectedUser.id ).then( function(id) {
$scope.buildMenu();
});
});
}
}, function () {
//console.log('Modal Student dismissed at: ' + new Date());
});
}

In case its a modal where you are passing the existing students objects, your controller code should be modified as:
Also you should use two separate views in this case for add and edit to avoid code cluttering. Because in case of addition students will be an array of objects and in case of edit it will be a single object where you cannot use ng-repeat as it wont work
app.controller('MainCtrl', function($scope, $modalInstance, students) {
//students variable contains information about the student to be edited, so your code should be something like this
if(students.classname !== undefined){
$scope.students = students;
}else{
$scope.students = [];
}
// rather than re-initializing each time modal gets opened you should retain value from students that you are passing
$scope.addNewStudent = function() {
$scope.students.push({
classname: "",
firstname: "",
lastname: ""
});
};
$scope.removeStudent = function() {
var lastItem = $scope.students.length - 1;
$scope.students.splice(lastItem);
};
$scope.save = function() {
$modalInstance.close($scope.students);
//make sure to save this when modal closes in the variable you are returning students from when modal is triggered
};
$scope.delete = function() {
$scope.info['deleted'] = 1;
$modalInstance.close($scope.students);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});

Related

Angular ng-change not working for checkboxes

Here is my code below. The ng-change of individual checkboxes is not getting triggered when it is changed by clicking Select All button but it is getting triggered when it's selected individually. I need the itemChecked method to be triggered when the Select All button is clicked.
Here is a Codepen Link for the same
HTML
<div ng-app="Test">
<div ng-controller="TestController">
<form>
<div ng-repeat="item in list track by $index">
<input type="checkbox" ng-model="item" ng-change="itemChecked($index)">{{$index + 1}}
</div>
</form>
<button ng-click="toggleSelection()">Select all</button>
</div>
</div>
JavaScript
var app = angular.module("Test", []);
app.controller("TestController", [
"$scope",
"$http",
function($scope, $http) {
$scope.list = [false, false, false, false, false];
$scope.itemChecked = function(i) {
console.log(i);
};
$scope.toggleSelection = function() {
for (var i in $scope.list) {
$scope.list[i] = true;
}
};
}
]);
Please let me know what I need to change or what I am doing wrong to fix this.
You have set wrong variable in ng-model. The ng-model section should be:
ng-model="list[$index]"
To listen the collection, you have to use the following:
$scope.$watchCollection
It is working perfectly in the following code, check the code snippet:
var app = angular.module("Test", []);
app.controller("TestController", [
"$scope",
"$http",
function($scope, $http) {
$scope.list = [false, false, false, false, false];
$scope.itemChecked = function(i) {
console.log(i);
console.log($scope.list[i]);
};
$scope.$watchCollection('list', function (oldValue, newValue) {
//console.log(oldValue);
//console.log(newValue);
//console.log($scope.list);
for(var i = 0; i < oldValue.length;i++){
if (oldValue[i]!==newValue[i]) {
$scope.itemChecked(i);
}
}
});
$scope.toggleSelection = function() {
for (var i in $scope.list) {
$scope.list[i] = true;
}
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Test">
<div ng-controller="TestController">
<form>
<div ng-repeat="item in list track by $index">
<input type="checkbox" ng-model="list[$index]" ng-change="itemChecked($index)">{{$index + 1}}
</div>
</form>
<button ng-click="toggleSelection()">Select all</button>
</div>
</div>
What you need is watchCollection method. ngChange works only if the value is changed from HTML. It is not triggered when the value is changed from controller.
app.controller("TestController", [
"$scope",
"$http",
function($scope, $http) {
$scope.list = [false, false, false, false, false];
$scope.itemChecked = function(i) {
console.log(i);
};
$scope.toggleSelection = function() {
for (var i in $scope.list) {
$scope.list[i] = true;
}
};
/*********************************************************/
$scope.$watchCollection('list', function (newVal, oldVal) {
console.log('collection changed') });
}
/*********************************************************/
]);
Or If you just want itemChecked method to be called whenever the selectAll button is clicked, Then just call itemChecked inside toggleSelection method.
$scope.toggleSelection = function() {
for (var i in $scope.list) {
$scope.list[i] = true;
$scope.itemChecked(i);
}
};

#ModelAttribute in my REST comes empty

I am trying to pass data through <select multiple> from HTML to my RESTful.
That data is an array of String. I don't know why when it comes to my backend it's empty.
This is my REST:
#PutMapping("/events")
#Timed
public ResponseEntity<Event> updateEvent(#RequestBody Event event, #ModelAttribute("attendeesToParse") ArrayList<String> attendeesToParse) throws URISyntaxException {
//Some code
}
This is my HTML:
<div class="form-group">
<label>Attendees</label>
<select class="form-control" multiple name="attendeesToParse" ng-model="vm.usernames"
ng-options="customUser as customUser.username for customUser in vm.customusers">
<option value=""></option>
</select>
</div>
I tried to fix this one for days, I googled it so much but I found no solutions. Please help me.
I can not change my HTML into a JSP due to my project's structure and business logic.
Why does it come empty? If I try to show some logs I see an empty array [].
UPDATE
My HTML form call:
<form name="editForm" role="form" novalidate ng-submit="vm.save()">
<!-- some code -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
<span class="glyphicon glyphicon-ban-circle"></span> <span data-translate="entity.action.cancel">Cancel</span>
</button>
<button type="submit" ng-disabled="editForm.$invalid || vm.isSaving" class="btn btn-primary">
<span class="glyphicon glyphicon-save"></span> <span data-translate="entity.action.save">Save</span>
</button>
</div>
</form>
My event-dialog-controller.js: (is the .js controller that works with form)
(function() {
'use strict';
angular
.module('businessRequestApp')
.controller('EventDialogController', EventDialogController);
EventDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Event', 'Desk', 'CustomUser'];
function EventDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, entity, Event, Desk, CustomUser) {
var vm = this;
vm.event = entity;
vm.clear = clear;
vm.datePickerOpenStatus = {};
vm.openCalendar = openCalendar;
vm.save = save;
vm.reftables = Desk.query({filter: 'event-is-null'});
$q.all([vm.event.$promise, vm.reftables.$promise]).then(function() {
if (!vm.event.refTable || !vm.event.refTable.id) {
return $q.reject();
}
return Desk.get({id : vm.event.refTable.id}).$promise;
}).then(function(refTable) {
vm.reftables.push(refTable);
});
vm.customusers = CustomUser.query();
$timeout(function (){
angular.element('.form-group:eq(1)>input').focus();
});
function clear () {
$uibModalInstance.dismiss('cancel');
}
function save () {
vm.isSaving = true;
if (vm.event.id !== null) {
Event.update(vm.event, onSaveSuccess, onSaveError);
} else {
Event.save(vm.event, onSaveSuccess, onSaveError);
}
}
function onSaveSuccess (result) {
$scope.$emit('businessRequestApp:eventUpdate', result);
$uibModalInstance.close(result);
vm.isSaving = false;
}
function onSaveError () {
vm.isSaving = false;
}
vm.datePickerOpenStatus.date = false;
function openCalendar (date) {
vm.datePickerOpenStatus[date] = true;
}
}
})();
My event-service.js:
(function() {
'use strict';
angular
.module('businessRequestApp')
.factory('Event', Event);
Event.$inject = ['$resource', 'DateUtils'];
function Event ($resource, DateUtils) {
var resourceUrl = 'api/events/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.date = DateUtils.convertLocalDateFromServer(data.date);
}
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
}
});
}
})();
My event.controller.js:
(function () {
'use strict';
angular
.module('businessRequestApp')
.controller('EventController', EventController);
EventController.$inject = ['Event', 'CustomUser', '$scope'];
function EventController(Event, CustomUser, $scope) {
var vm = this;
vm.events = [];
vm.customUsers = [];
vm.usernames = ["test1", "test2", "test3"];
$scope.allCustomUsers = [];
loadAll();
function loadAll() {
Event.query(function (result) {
vm.events = result;
vm.searchQuery = null;
});
CustomUser.query(function (result) {
vm.customUsers = result;
vm.searchQuery = null;
for (var i = 0; i < vm.customUsers.length; i++) {
$scope.allCustomUsers.push(vm.customUsers[i].username);
}
});
}
}
})();
If you're using angularJS, you can't data bind data with #ModelAttribute, because #ModelAttribute exists only with template engines such as JSP, and AngularJS is not a template engine within Spring. Try instead to use #RequestBody on String parameter, and then extract the data using Jackson.
One more issue, How exactly do you pass your values from front to back? I don't see any $http angularJS call, and no HTML form with POST method.

How to add a new element to a table from a pop up window using angularjs

I'm working on this simple customers table information such as: name, lastname and age. I created a function that allows users to add a new customer and that works just fine :). I also created a pop up window and I want to add the new customer from the pop up window. My pop up window works fine, but I cannot add a new customer from it. Please help me. Thank you so much!!.
Here's my code that runs just fine
<script type="text/javascript">
var App = angular.module('sortApp', ['ui.bootstrap'])
App.controller('mainController', function($scope, $modal, $log, $filter) {
$scope.sortType = 'id'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchPerson = ''; // set the default search/filter term
// Array - List of People
$scope.People = [
{ id: 1, name: 'Mike', Lastname: 'White', age: 26 },
{ id: 2, name: 'Carl', Lastname: 'Barns', age: 41 },
{ id: 3, name: 'Deb', Lastname: 'McDonals',age: 78 },
{ id: 4, name: 'Tommy', Lastname: 'Humbs', age: 32 }
];
/*
This function adds a new customer
*/
$scope.addPerson = function(){
var customer = {
name: $scope.name,
Lastname: $scope.Lastname,
age: $scope.age,
};
$scope.People.push(customer);
};
/*
This function removes a customer
*/
$scope.removePerson = function(index){
$scope.People.splice(index, 1);
};
$scope.openPopupScreen = function() {
var modalInstance = $modal.open({
template: '<div class="modal-header"> <a class="close" data- dismiss="modal" ng-click="cancel()">X</a><h1>Add Customer</h1></div><div class="modal-body"> <form >' +
' <label>Name:</label><input type="text" class="span3" ng-model="name"></br>' +
' <label>Lastname:</label><input type="text" class="span3" ng-model="Lastname"></br>' +
' <label>Age:</label><input type="number" class="span3" ng-model="age"></br>' +
' <button type="submit" class="btn btn-success" ng-click="addPerson()">Add In List</button>' +
' <button type="reset" class="btn ">Clear</button>' +
' </form>' +
'</div>' +
'<div class="modal-footer">' +
' <a data-dismiss="modal" aria-hidden="true" class="btn btn-primary" ng-click="cancel()">close</a>' +
'</div>',
controller: ModalInstanceCtrl
});
};
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
});
</script>
In your modal, you call addPerson() but that function is in mainController, not in modal controller so it's not working
You need to provide a function to get result in modal and pass it back to main controller, .e.g. in ModalInstanceCtrl:
$scope.newPerson = {
//Bind ng-model from modal input to properties of this
};
$scope.add = function() {
//Pass newPerson to caller from main controller
$modalInstance.close($scope.newPerson);
};
Remember to bind add() to button click:
<button type="button" class="btn btn-success" ng-click="add()">Add In List</button>
In main controller:
var modalInstance = $modal.open({
//create modal
});
modalInstance.result.then(function (newPerson) {
$scope.addPerson(newPerson);
}, function () {
//User clicks dismiss instead of add
});
Also, Within the form in your modal popup, you should consider changing the ng-model values for all fields to something like "newPerson.name", "newPerson.age" and so on. AFAIK when you have an ng-model attribute and there is no 'dot' in there, you are doing it wrong. So within your mainController declare an empty object $scope.newPerson and then when adding a newPerson, add the values like name and age to this object.

AngularsJS list and edit with 2 controllers

I try to do my first angularjs application, but i have a problem. I have 2 controllers (and i would like to keep 2): the first to list items, the second to edit or create an item.
When I save an item, or create a new item, i can't edit another or create another, after to do one action the form can't load or save... The problem seems to be this line :
$scope.editPlace = {};
But I don't understand why...
DEMO :
http://jsfiddle.net/cxL7qmke/
HTML:
<div ng-app="mapApp">
<div ng-controller="EditPlaceCtrl">
<form name="editPlaceForm">
<fieldset>
<label for="title">Title:</label>
<input id="title" type="text" ng-model="editPlace.title">
<input type="hidden" ng-model="editPlace.id" />
<button type="submit" ng-click="savePlace()">Save</button>
</fieldset>
</form>
</div>
<section ng-controller="PlaceCtrl">
<ul>
<li ng-repeat="place in places">
<label>{{place.title}} edit</label>
</li>
</ul>
</section>
</div>
JS :
var mapApp = angular.module('mapApp', []);
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
$rootScope.editPlace = angular.copy(placeService.get(id));
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.savePlace = function () {
placeService.save($scope.editPlace);
$scope.editPlace = {};
}
});
mapApp.service('placeService', function ($filter) {
var uid = 3;
var places = [
{ id: 1, title: 'Item1', lat: 43.123, lng: -89.123 },
{ id: 2, title: 'Item2', lat: 43.321, lng: -89.321 }
];
this.getAll = function () {
return places;
}
this.get = function (id) {
var place, i;
for (i in places) {
if (places[i].id === id) {
return places[i];
}
}
return false;
};
this.save = function (place) {
if (place.id == null) {
place.id = this.uid++;
places.push(place);
} else {
for (i in places) {
if (places[i].id == place.id) {
places[i] = place;
}
}
}
};
});
I've made few changes and seems to work for me please see here
http://jsfiddle.net/m9bevovy/
in your service I've added
this.newPlace = {};
this.setNew = function (id) {
this.newPlace = this.get(id);
};
and your controllers :
mapApp.controller('PlaceCtrl', function ($scope, $rootScope, placeService) {
$scope.places = placeService.getAll();
$scope.edit = function (id) {
placeService.setNew(id);
}
});
mapApp.controller('EditPlaceCtrl', function ($scope, placeService) {
$scope.placeService = placeService;
$scope.savePlace = function () {
placeService.save($scope.placeService.newPlace);
$scope.placeService.newPlace = {};
}
});
You are using both $scope and $rootScope to hold the reference to editPlace.
If you want to use the $rootScope, use this in your savePlace function:
$rootScope.editPlace = {};
Instead of:
$scope.editPlace = {};
Here`s the working fiddle

How to pass input value to controller in Angular Modal service

Using this angular modal service:
app.service('modalService', ['$modal',
function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: '/templates/modal.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function () {
$modalInstance.dismiss('cancel');
};
}
}
return $modal.open(tempModalDefaults).result;
};
}]);
I'm having trouble understanding how to pass values from the modal (which has an input) to the controller.
This is my modal:
<input type="text" class="form-control" id="{{modalOptions.inputName}}" name="{{modalOptions.inputName}}" data-ng-model="modalOptions.inputVal" data-ng-if="modalOptions.inputName" />
<button type="button" class="btn"
data-ng-click="modalOptions.close()">{{modalOptions.closeButtonText}}</button>
<button class="btn btn-primary"
data-ng-click="modalOptions.ok();">{{modalOptions.actionButtonText}}</button>
Controller:
$scope.addTopic = function () {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Create Topic',
inputName: 'topicName'
};
modalService.showModal({}, modalOptions).then(function (result) {
// I tried...
var input = $scope.inputName; // and...
input = result;
$log.log("Adding topic '" + input + "' to publication no " + $scope.publication.id);
});
}
So the input is an option in modalOptions but when the user enters a value and clicks ok, nothing is sent to the controller. $scope.inputName returns undefined and so does result.
Ideally, I want to end up with an object like so { inputs : {name: 'inputName' , value: 'abcde'} }.
Try the resolve method in Angular UI Bootstrap
var modalOptions = {
resolve: {
myvar: function () {
return $scope.myvar;
}
}
};
modalService.showModal(modalOptions);

Categories

Resources