AngularJs - how to reload page after adding new data to datatable - javascript

I am very new to angularjs and using angularjs bootstrap datatable. Now when I add new record to my datatable it is being updated in mysql database but I need to reload my page so new record can be displayed in table also but I don't know how to do it. Can anyone please help me? Can I init tableRoleCtrl on success of addRoleData() in ui-bootstrp.js?
Here is my code
ui-bootstrap.js
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, content, tableService) {
//add new role
$scope.addRole = function(w) {
tableService.addRoleData(w)
}
})
table.js
.controller('tableRoleCtrl', function($filter, $sce, ngTableParams, tableService) {
//var data = tableService.data;
var self = this;
var promise = tableService.getRoleData();
self.data = [];
promise.then(
function(payload) {
self.data = payload.data;
//alert(JSON.stringify(self.data));
//console.log("test" + self.data)
self.tableEdit = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: self.data.length, // length of data
getData: function($defer, params) {
$defer.resolve(self.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
},
function(errorPayload) {
$log.error('failure loading movie', errorPayload);
});
//to updaate data
self.updateRole = function(w) {
tableService.updateRoleData(w);
}
})
service.js
.factory('tableService', ['$http', function($http){
var _this = this;
return {
// role
getRoleData: function() {
return $http.get("data/getRoles.php");
},
updateRoleData: function(w) {
$http.post("data/updateRole.php", w)
},
addRoleData: function(w) {
$http.post("data/addRole.php", w)
}
}
}])
html
<div data-ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="addrole.html">
<div class="modal-header">
<h4 class="modal-title">Add Role</h4>
</div>
<div class="modal-body m-l-15">
<form role="form">
<div class="row">
<div class="col-md-8">
<div class="input-group">
<span class="input-group-addon"><i class="zmdi zmdi-account"></i></span>
<div class="fg-line">
<input type="text" name="role_title" ng-model="add_role.role_title" class="form-control" placeholder="Title">
</div>
</div>
<br/>
<div class="">
<div class="input-group"><span class="input-group-addon"><i class="zmdi zmdi-account-circle"></i></span>
<select chosen multiple>
<option>Use seetings from</option>
<option>HR</option>
<option>Employee</option>
<option>Admin</option>
</select>
</div>
</div>
</div><br/>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="ok(); addRole(add_role)">Submit</button>
<button class="btn btn-link" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="openStatic('addrole')">Add Roles</button>
</div>
<div class="table-responsive">
<table ng-table="tctrl.tableEdit" class="table table-striped" show-filter="true">
<tr ng-repeat="w in $data" ng-class="{ 'active': w.$edit }" ng-click="ShowHide12()" style="cursor:pointer">
<a href="" ng-click="getSingleRole()">
<td><span ng-if="!w.$edit">{{ w.rl_title }}</span>
<div ng-if="w.$edit"><input class="form-control" type="text" ng-model="w.rl_title" /></div>
</td>
</a>
<td>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = true; "><i class="zmdi zmdi-edit"></i></button>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = false"><i class="zmdi zmdi-close"></i></button>
<button type="button" class="btn btn-success" ng-if="w.$edit" ng-click="w.$edit = false; tctrl.updateRole(w)"><i class="zmdi zmdi-check"></i></button>
<button type="button" class="btn btn-default" ng-if="w.$edit" data-ng-click="w.$edit = 0" ><i class="zmdi zmdi-close"></i></button>
</td>
</tr>
</table>
</div>

You don't actually need to reload page when data is updated, AngularJS is MVC framework and each model AngularJS will create a watcher to update view.
Basically, you just need to store your table data to a scope variable $scope.tableData in your controller then use ng-repeat="row in tableData" to iterate your table data. ng-repeat will watch your tableData changes then update your table.

If you changed the ngTable data dynamically, you can refresh it with:
self.tableEdit.reload();

Related

How to pass the form values with array to angular controller

I have a functionality to select the document and add the file that document type.
Iam unable to send that values to the controller.
Actually i am using add new functionality to the form. So i name it as array and trying to send the details. But iam not getting the details here.
FYI i am using codeigniter for the server scripting.
Can any one help me out.
Here is my view file checklist.php.
<div ng-controller="checklist">
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<form class="form-horizontal" role="form" name="checkForm" action="#/customer/adddocument" novalidate>
<a id="button" onlick="duplicate()">Click me</a>
<div id="duplicater">
<div class="row">
<div class="form-group col-md-6" ng-controller="documentController" >
<label class="col-sm-3 control-label no-padding-right">Documents</label>
<div class="col-sm-9">
<select class="form-control" name="document[]" required ng-model = "checklist.document[]">
<option value="">Select document</option>
<option ng-repeat="option in documentsList.data" value="{{option.AGENT_ID}}">{{option.AGENT_NAME}}</option>
</select>
</div>
</div>
<div class="col-md-6">
<input type="file" name="file" />
</div>
</div>
</div>
<script>
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
// clone.id = "duplicetor" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
</script>
<div class="modal-footer" >
<button ng-show="sub" ng-click="submit(checklist)" ng-disabled="checkForm.$invalid" class="btn btn-sm btn-primary">
<i class="ace-icon fa fa-check"></i>
Save
</button>
<button ng-show="edt" ng-click="update(checklist)" ng-disabled="checkForm.$invalid" class="btn btn-sm btn-primary">
<i class="ace-icon fa fa-check"></i>
Edit
</button>
<button ng-show="edt" ng-click="cancel()" class="btn btn-sm btn-primary">
<i class="ace-icon fa fa-check"></i>
Cancel
</button>
</div>
<input type="submit" name="submit">
</form>
And here is my controller file checklist.js.
project.controller('checklist', ['$scope', '$http', 'services', '$location', 'uiGridConstants', '$timeout','$interval','$q','$rootScope','$filter', function($scope, $http, services, $location, uiGridConstants, $timeout,$interval,$q,$rootScope,$filter,uibDateParser) {
$rootScope.$broadcast("globalgrid",{'displaycolumns': discolumns, 'gridservice':gridservice , 'grid_service_param':grid_service_param });//,'gridload':func_name, 'addnew': "Submit"
//$scope.selectedDate = Date();
$scope.sub = true;
$scope.edt = false;
$scope.uploadfiles = "";
console.log($scope.date);
$scope.custsub = function(e){
var fd = new FormData();
fd.append('file', $scope.uploadfiles);
var f = $scope.uploadfiles;
console.log(f);
console.log(e);
services.addCustomerinfo(res.data,e.icno,e.customername);
$rootScope.submit(submitfun);
});
}
in the controller when i check with console i am not getting anything.
can any one help me out.
1.) You need to create a rest api which returns your posted data from form,
2.) create an angular service which makes a request from that api,
3.) include that service in your controller and send retrieved data to view.

Form data not showing after post in AngularJS

I am trying to post a form data but the content are not updated on the UI.
The following code is working it does post the data but the tags are not updated in the {{tag.Title}}.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var new1 = data;
$scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
<div class="row" data-ng-repeat="tagsByType in consultantCv.TagsbyTypes" ng-init="init('tag',2000)">
<div class="col-md-12">
<hr />
<h2>
<i class="icons8-{{tagsByType.CssClass}}" aria-hidden="true"></i>{{tagsByType.Title}}
</h2>
<div class="tags">
<div class="input-group" ng-controller="consultantController">
<div ng-repeat="tag in tagsByType.Tags" class="tag label label-success">
{{tag.Title}}
<a class="close" href ng-click="removeTag(tag)">×</a>
</div>
<form ng-submit="saveTag(Title,tagsByType.Id)" role="form">
<input type="text" ng-model="Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>
</div>
</div>
</div>
</div>
Push your data as object with same property name.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var newData = {
Title : data,
}
$scope.consultantCv.TagsbyTypes[0].Tags.push(newData);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
Found the issue was that tagsType was not passed to the controller.
Fixed it by the following code
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(result){
TagTypeId.Tags.push(result);
$scope.consultantCv.TagsbyTypes.Tags.push(newData);
//$scope.consultantCv.TagsbyTypes[0].Tags.push(new1);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
};
<form ng-submit="saveTag(tag.Title,tagsByType)" role="form">
<input type="text" ng-model="tag.Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>

Sharing data between different controllers

I want to build a small application (for learning Angular JS) that can define a list of locations and a list of events. The application was developed based on the tutorial found here: http://g00glen00b.be/prototyping-spring-boot-angularjs/.
When defining a new event I would like to associate a location for the new event. The location should be selected using a combobox.
So first I define 2 locations, let's say Location 1 and Location 2. I want to bind somehow the list of available locations (1 and 2) to the combobox labeled "Location select" see this image
So far I was able to bind the location list to the combobox, but the items of the combobox are updated only when I refresh the browser. I would like to be able to automatically refresh the content of the combobox whenever the list of available locations is changed (a new location is added or a location is removed).
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet"
href="./bower_components/bootstrap-css-only/css/bootstrap.min.css" />
</head>
<body ng-app="myEventApp">
<div class="container" ng-controller="EventAppController" >
<div class="page-header">
<h1>Edit Events</h1>
</div>
<div class="alert alert-info" role="alert"
ng-hide="events && events.length > 0">There are no events yet.
</div>
<form class="form-horizontal" role="form"
ng-submit="addEvent(newEventName,newEventDescription)" ng-controller="LocationAppController">
<div >Locations: {{locations}}</div>
<div class="form-group" ng-repeat="event in events">
<div class="checkbox col-xs-9">
<label> <strong>{{event.name}}</strong> /
{{event.description}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button"
title="Delete" ng-click="deleteEvent(event)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr />
<div class="input-group">
<input type="text" class="form-control" ng-model="newEventName"
placeholder="Enter the name..." /> <input type="text"
class="form-control" ng-model="newEventDescription"
placeholder="Enter the description..." />
<label for="locationSelect">Location select: </label>
<select
name="locationSelect" id="locationSelect" ng-model="data.repeatSelect">
<option value="">---Please select---</option>
<option ng-repeat="location in locations"
value="{{location.id}}">{{location.name}}</option>
</select>
<div class="col-md-6"></div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"
ng-disabled="!newEventName||!newEventDescription" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<!-- Location -->
<div class="container" ng-controller="LocationAppController">
<div class="page-header">
<h1>Edit Locations</h1>
</div>
<div class="alert alert-info" role="alert"
ng-hide="locations && locations.length > 0">There are no
locations defined yet.</div>
<form class="form-horizontal" role="form"
ng-submit="addLocation(newLocationName,newLocationAddress)">
<div class="form-group" ng-repeat="location in locations">
<div class="checkbox col-xs-9">
<label> <strong>{{location.name}}</strong> /
{{location.address}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button"
title="Delete" ng-click="deleteLocation(location)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr />
<div class="input-group">
<input type="text" class="form-control" ng-model="newLocationName"
placeholder="Enter the name..." /> <input type="text"
class="form-control" ng-model="newLocationAddress"
placeholder="Enter the address..." />
<!-- <label>Location: </label> -->
<!-- <select -->
<!-- name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect"> -->
<!-- <option ng-repeat="option in data.availableOptions" -->
<!-- value="{{option.id}}">{{option.name}}</option> -->
<!-- </select> -->
<div class="col-md-6"></div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"
ng-disabled="!newLocationName||!newLocationAddress" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<script type="text/javascript"
src="./bower_components/angular/angular.min.js"></script>
<script type="text/javascript"
src="./bower_components/angular-resource/angular-resource.min.js"></script>
<script type="text/javascript"
src="./bower_components/lodash/dist/lodash.min.js"></script>
<script type="text/javascript" src="./app/eventApp.js"></script>
<script type="text/javascript" src="./app/eventControllers.js"></script>
<script type="text/javascript" src="./app/eventServices.js"></script>
<script type="text/javascript" src="./app/locationControllers.js"></script>
<script type="text/javascript" src="./app/locationServices.js"></script>
<script type="text/css" src="./app/custom.css"></script>
</body>
</html>
And these are the controllers used:
eventControllers.js
(function(angular) {
var EventAppController = function($scope, Event) {
Event.query(function(response) {
$scope.events = response ? response : [];
});
$scope.addEvent = function(name, description) {
new Event({
locations:[],
name : name,
description : description,
}).$save(function(event) {
$scope.events.push(event);
});
$scope.newEventName = "";
$scope.newEventDescription = "";
};
$scope.updateEvent = function(event) {
event.$update();
};
$scope.deleteEvent = function(event) {
event.$remove(function() {
$scope.events.splice($scope.events.indexOf(event), 1);
});
};
};
EventAppController.$inject = [ '$scope', 'Event' ];
angular.module("myEventApp.controllers").controller("EventAppController",
EventAppController);
}(angular));
locationControllers.js
(function(angular) {
var LocationAppController = function($scope, Location) {
Location.query(function(response) {
$scope.locations = response ? response : [];
});
$scope.addLocation = function(name, address) {
new Location({
name: name,
address: address,
}).$save(function(location) {
$scope.locations.push(location);
});
$scope.newLocationName = "";
$scope.newLocationAddress = "";
};
$scope.updateLocation = function(location) {
location.$update();
};
$scope.deleteLocation = function(location) {
location.$remove(function() {
$scope.locations.splice($scope.locations.indexOf(location), 1);
});
};
return {
getLocations: function() {
return $scope.locations;
}
}
};
LocationAppController.$inject = ['$scope', 'Location'];
angular.module("myEventApp.controllers").controller("LocationAppController", LocationAppController);
}(angular));
eventServices.js
(function(angular) {
var EventFactory = function($resource) {
return $resource('/event/:id', {
id : '#id'
}, {
update : {
method : "PUT"
},
remove : {
method : "DELETE"
}
});
};
EventFactory.$inject = [ '$resource' ];
angular.module("myEventApp.services").factory("Event", EventFactory);
}(angular));
locationServices.js
(function(angular) {
var LocationFactory = function($resource) {
return $resource('/location/:id', {
id : '#id'
}, {
update : {
method : "PUT"
},
remove : {
method : "DELETE"
}
});
};
LocationFactory.$inject = [ '$resource' ];
angular.module("myEventApp.services").factory("Location", LocationFactory);
}(angular));
So, the question is: how to automatically update the content of the combobox when a new location is added / a location is deleted? Thank you.

send data from my controller to my ngDialog

In my controller i have this code, i get the id from one table in the html template and get one object from services and return to ngDialog to show to Edit this data and save in my api-rest:
(function() {
'use strict';
angular
.module('app')
.controller('FraseController', FraseController);
FraseController.$inject = ['FraseService','ngDialog'];
function FraseController(FraseService,ngDialog) {
var vm = this;
vm.texto = rpeuba;
vm.iden = 0;
vm.efrase = '';
vm.edit = function(){
FraseService.get().then(function(response){
console.log(response.data.response);
vm.efrase = response.data.response;
ngDialog.open({
template: 'newFrase',
scope: this
});
});
}
}
}());
and in this html code:
<script type="text/ng-template" id="newFrase">
<h1>Nueva Frase {{vm.texto}}</h1>
<div class="modal-body">
<div class="row">
<div class="form-group">
<label for="frase" class= "col-lg-2 espaciar">Frase: </label>
<div class="col-lg-10">
<input ng-model="frase.efrase.frace" type="text" name="frase" id="frase" class="form-control" placeholder="Escriba su frace aquí">
</div>
<br>
<label for="autor" class= "col-lg-2 control-label espaciar">Autor: </label>
<div class="col-lg-10 ">
<input type="text" name="autor" name="autor" class="form-control" placeholder="Escriba el Autor aquí">
</div>
<br>
<label class="col-lg-2 espaciar">Banner: </label>
<div class="col-lg-10">
<select name="banner" class="form-control selectize-input espaciar">
<option value="0"><< Ninguno >></option>
<option ng-repeat="itemb in FraseController.lbanner" value="{{itemb.id}}">
{{itemb.titulo}}
</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-default"
ng-click="closeThisDialog('tiempo')">Cancelar</button>
<input name="submit" value="Insertar" class="btn btn-primary" title="Insertar" type="submit">
</div>
</script>
i want to show data from my controller in my ngDialog to Edit a one Frase
Good morning, here are how to solve all my problems with ngDialog.
as I run for an answer to what I call ngDialog.openConfirm and on the response run my controller methods mother and passed as a parameter an object from which consume your data.
This is my code to delete a frase.
JS in my controller:
vm.drop = function(__frase){ //Drop the frase
ngDialog.openConfirm({
template: '<h3>You are sure to delete the phrase<h3> '+
'<div class="modal-footer"> '+
'<button type="button" '+
'ng-click=closeThisDialog("Cancel") '+
'class="btn btn-default">Cancel'+
'</button> '+
'<button type="button" '+
'ng-click=confirm(dfrase.frase.id) '+
'class="btn btn-primary">Delete</button> '+
'</div>',
plain:true,
controllerAs: 'dfrase',
controller: [function() {
var vm = this;
vm.frase = __frase;
}]
})
.then(
function(value) { //ok
FraseService.drop(value).then(function(response) {
console.log(response.data.response);
});
refresh();
},
function(value) { //cancel
console.log(value);
}
);
}
FraseService consumer that is a factor with which it interacted with my api and refresh method refreshes me the frase list items.
D greetings

Getting data from modal AngularJS

I am trying to get data FROM modal to invoking controller, and all the examples I have found only describe way to get data to modal.
What is the proper way to do it?
This is a form I am using in modal:
<form class="form-horizontal">
<div class="modal-body">
<div class="control-group">
<label class="control-label">Name:</label>
<div class="controls">
<input type="text" ng-model="transaction.name" placeholder="Transaction name" />
</div>
</div>
<div class="control-group">
<label class="control-label">Category</label>
<div class="controls">
<input type="text" ng-model="transaction.category" placeholder="Category" />
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="text" ng-model="transaction.amount" placeholder="Amount" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date</label>
<div class="controls">
<input type="text" datepicker-popup="dd-MMMM-yyyy" ng-model="transaction.date" is-open="opened" min="minDate" max="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" />
<button class="btn" ng-click="open()"><i class="icon-calendar"></i></button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn pull-left" data-dismiss="modal">
<i class="icon-remove"></i> Cancel
</button>
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction()">
<i class="icon-ok icon-white"></i> Save Changes
</button>
</div>
These are controllers:
moneyApp.controller("TransactionController", function($scope, $http, $modal, $log) {
console.log("modal: ", $modal);
$scope.transaction = {}
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'partials/modal.html',
controller: 'ModalInstanceController',
resolve: {
transaction: function() {
return $scope.transaction;
}
}
});
modalInstance.result.then(function (receivedTransaction) {
$scope.selected = receivedTransaction;
console.log("Transaction received: ", transaction);
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$http({method: 'GET', url: 'transactions/15/all/'}).success(function(data) {
$scope.transactions = data; // response data
});
})
and
moneyApp.controller("ModalInstanceController", function($scope, $modalInstance, $http, transaction) {
$scope.createTransaction = function() {
console.log("Transakcja: ", $scope.transaction);
$scope.transaction.budgetId = 15;
$scope.selected = {
item: $scope.transaction
}
$http({method: 'POST', url: 'transactions/add/', data : $scope.transaction, headers:{'Accept': 'application/json', 'Content-Type': 'application/json; ; charset=UTF-8'}}).success(function(data) {
console.log("Transaction succesfully added to a DB...");
});
}
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
When I am trying to invoke method createTransaction, $scope.transaction is undefined. How to get data from this form?
I think you need to assign transaction to $scope.transaction in your ModalInstanceController because you are passing in the transaction object but not putting it into $scope.
$scope.transaction = transaction
In your Modal form you need to pass the ng-model object(ie transaction) to the function (createTransaction()) which gets called on form submit.
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction(transaction)">
<i class="icon-ok icon-white"></i> Save Changes
</button>
And in your controller add the object as parameter to the java-script function.
$scope.createTransaction = function(transaction) {
console.log("transaction details: "+ transaction.category+" "+transaction.amount);
};
Let me know if you are facing any issues, i can share the working code of mine.

Categories

Resources