How could I update a Datatable in modal using AngularJS - angularjs

I have been stuck in something simple that I think I haven't solved yet because of a lack of experience. Here is the catch I have a very simple controller which load the data from a service when I first Load the modal but once I tried to use the CRUD operations (hopefully working!!) the datatable doesn't update. I will share the code. Thanks of all.
I need that after insert, for example, the datatable update meaning rerender the current list of elements.
Call of the Modal
vm.openBooksModal = function (authorId) {
var modalInstance = $uibModal.open({
templateUrl: '/app/book/index.html,
controller: 'BooksController',
size: '',
resolve: {
authorId: function () {
return authorId;
}
}
});
Modal Controller
(function () {
'use strict';
angular.module('bookApp').controller('BooksController', BooksController);
BooksController.$inject = ['$uibModalInstance', '$scope', 'authorId', 'bookService', 'DTOptionsBuilder', 'DTColumnDefBuilder',
'DTColumnBuilder', 'dtUtils','alertService'];
function NotesController($uibModalInstance, $scope, authorId, bookService, DTOptionsBuilder, DTColumnDefBuilder,
DTColumnBuilder, dtUtils, alertService) {
$scope.authorId= authorId;
$scope.book= {
id: 0,
title:''
};
//if (angular.isDefined())
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
$scope.dtBooksColumnDefs = [
DTColumnDefBuilder.newColumnDef(0).notSortable()
];
$scope.dtBooksOptions = DTOptionsBuilder
.newOptions()
.withOption('bFilter', false)
.withOption('order', [[2, 'desc']])
.withOption('aaSorting', [])
.withOption('lengthMenu', [[5, 10, 25, 50], [5, 10, 25, 50]]);
$scope.dtBooksInstance = {};
$scope.LoadData = LoadData();
function LoadData(){
return bookService.getBook($scope.authorId).$promise
.then(getBookCompleted, handleError);
}
$scope.save = function (newTitle) {
$scope.book.title= newTitle;
bookService.saveBook($scope.book.id, $scope.authorId, $scope.book.title).$promise
.then(saveBookCompleted, handleError);
LoadData();
}
$scope.editBook= function( book){
$scope.book= book;
$scope.newTitle= book.title;
}
$scope.deleteBook = function( book){
bookService.deleteBook(book.id).$promise
.then(saveBookCompleted, handleError);
}
//private methods
function getBookCompleted(data) {
$scope.leadBookList = data;
debugger;
if (angular.isDefined($scope.dtBookInstance.rerender)) {
$scope.dtBooksInstance.rerender();
}
$scope.book= { };
$scope.newTitle = '';
}
function saveBookCompleted() {
bookService.getBook($scope.authorId).$promise
.then(getBookCompleted, handleError);
}
function handleError(response) {
alertService.error("Error trying to add a Note. Please try again later or contact IT.");
}
}
})();
HTML TEMPLATE
<div class="modal-header">
<h3 class="modal-title">Books</h3>
</div>
<div class="modal-body">
<div class="book-container">
<div class="head">
</div>
<div class="book">
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<label class="control-label">{{headerLabel}}</label>
<textarea id="newTitle" class="comment-textarea" data-ng-model="newTitle" rows="8" cols="90"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<table id="tblBooks" datatable="ng" class="table table-striped table-bordered font-xs"
dt-options="dtBookOptions" dt-column-defs="dtBookColumnDefs" >
<thead>
<tr>
<th></th>
<th></th>
<th>Title</th>
<th>Created By</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in BookList">
<td>
<button class="btn btn-sm btn-warning" ng-click="editBook(book)">
<i class="fa fa-pencil"></i>
</button>
</td>
<td>
<button class="btn btn-sm btn-danger" ng-click="deleteBook(book)">
<i class="fa fa-trash-o"></i>
</button>
</td>
<td>{{book.title}}</td>
<td>{{book.createdBy}}</td>
<td>{{book.createdDate | date:'MM/dd/yyyy HH:mm:ss'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer margin-top-0">
<button class="btn btn-primary" ng-click="save(newBook)" data-ng-disabled="newTitle === ''">Save</button>
<button class="btn btn-primary" ng-click="cancel()">Close</button>
</div>
Thanks

You're calling getBookCompleted twice. First after save in the saveBookCompleted function and second in the loaddata function
$scope.save = function (newTitle) {
$scope.book.title= newTitle;
bookService.saveBook($scope.book.id, $scope.authorId, $scope.book.title).$promise
.then(saveBookCompleted, handleError);
// remove this line since you're already call saveBookCompleted
//LoadData();
}

Related

Can we use jquery function inside angularjs

I have one table in jquery,In which when I click delete icon I need to display bootstrap modal to perform delete action.I did it using jquery but I dont know to do it in angular..Can anyone give me some suggestions?
<body ng-app="intranet_App">
<div class="container">
<div class="modal" id="deleteProject">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="confirmMessage">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="confirmOk">Ok</button>
<button type="button" class="btn btn-default" id="confirmCancel">Cancel</button>
</div>
</div>
</div>
</div>
<div class="col-xs-12 margin20 padding table-responsive">
<table class="col-xs-12 table table-hover table-bordered" id="projectList" ng-controller="myCtrl">
<thead class="colorBlue">
<tr><th>Project Name</th><th>Client</th><th>Client Co-ordinator</th><th>Action</th></tr>
</thead>
<tbody id="projectListTBody" >
<tr ng-repeat="x in projectList | filter:ProjectName">
<td>{{ x.ProjectName}}</td>
<td>{{ x.Client}}</td>
<td>{{ x.OnsiteCoordinator}}</td>
<td>
<i class="fa fa-user-plus fa-2x" ng-click="addResource()"></i>
<i class="fa fa-edit fa-2x" ng-click="editProj(x.Id)"></i>
<i class="fa fa-trash fa-2x" data-toggle="modal" data-target="#myModal" data-dismiss="modal" ng-click="deleteProject(x.Id)"></i>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
<script>
var app = angular
.module("intranet_App", [])
.controller("myCtrl", function ($scope, $http) {
$scope.projDetails = [];
$http.post('/Project/getProjectsList')
.then(function (response) {
console.log(response)
$scope.projectList = response.data;
})
$scope.editProj = function (x) {
$scope.projectDetails(x);
window.location = "/Project/EditProject?id=" + x;
}
$scope.projectDetails = function (x) {
$scope.projDetails.push(x);
$scope.json = angular.toJson($scope.x)
console.log($scope.json)
}
$scope.addResource = function () {
window.location = "/Project/ProjectRes";
}
});
</script>
This is my jquery methods:
function deleteProject(control) {
event.stopPropagation()
id = $(control).closest('tr').attr('id');
confirmDialog("Are you sure do you want to delete this Project?", function () {
removeProject(id)
});
}
function removeProject(elem) {
var updatedBy = $("#userName").text();
var ajxObj = { id: elem};
$.ajax({
type: "POST",
url: "/project/ProjectDelete",
data: JSON.stringify(ajxObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$(".success").html("project Deleted successfully!");
$('.success').show();
setTimeout(function () {
$('.success').hide();
}, 1000);
loadProjectsList()
}
});
}
You can use bootstrap angular model popup.
for more information https://angular-ui.github.io/bootstrap/#!#modal

pushed data is not refelcting in a table using angular

the pushed data from the model is not reflecting in the first table. It is there in console. The fiddle link is attached with this please help me on this.
fiddle link ---- http://jsfiddle.net/8MVLJ/2649/
html=========
<script src="https://code.angularjs.org/1.4.9/angular.min.js"></script>
<script src="https://rawgit.com/dwmkerr/angular-modal-service/master/dst/angular-modal-service.js"></script>
<div class="container" ng-app="app" ng-controller="Controller">
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<th>Attribute Name</th>
<th>Attribute Value</th>
</thead>
<tbody>
<tr ng-repeat="newdetail in newDetails">
<td>
<p ng-model="detail">{{newdetail.attrName}} </p>
</td>
<td>
<p ng-model="detailValue">{{newdetail.userAttrValue}} </p>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-default" href ng-click="show()">Select Attribute</a>
<script type="text/ng-template" id="modal.html">
<div class=" ngdialog-messsage modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="close('Cancel')" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<th>
<input type="checkbox" ng-model="allSelected" ng-model-options="{getterSetter: true}">
</th>
<th>Attribute Name</th>
<th>Attribute Value</th>
</thead>
<tbody>
<tr ng-repeat="detail in details">
<td>
<input type="checkbox" ng-model="detail.Selected">
</td>
<td>
<p ng-model="detail">{{detail.attrName}}</p>
</td>
<td>
<select ng-model="detail.user_attr_value" ng-init="detail.user_attr_value=detail.attr_value_Ind.split(',')[0]" class="form-control full-width">
<option ng-repeat="option in detail .attr_value_Ind.split(',')" value="{{option}}">{{option}}</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<input type="button" class="btn btn-primary" value="Add Selected" ng-click="add();close('Cancel')">
<input type="button" class="btn btn-danger " ng-click="checkAll(details.length)" value="Clear">
</div>
</div>
</div>
</div>
</div>
</script>
</div>
</div>
</div>
js===================
var app = angular.module('app', ['angularModalService']);
app.controller('Controller', function($scope, $element, ModalService) {
$scope.newDetails = [{
"attrName": "userType",
"userAttrValue": "Customer",
"userOrGroupId": "aaaazzz8522",
}];
$scope.add = function() {
angular.forEach($scope.details, function(detail) {
if (detail.Selected == true) {
$scope.newDetails.push({
'attrName': detail.attrName,
'attrName': detail.user_attr_value
});
$element.modal('hide');
close($scope.newDetails, 500);
console.log("loop", $scope.newDetails);
}
});
};
$scope.show = function() {
ModalService.showModal({
templateUrl: 'modal.html',
controller: "Controller"
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {});
});
};
//=================================================
$scope.close = function(result) {
close(result, 600);
};
$scope.details = [{
"attrName": "region",
"attrType": "USER",
"attr_value_Ind": "CHN-N,CHN-S,CHN-C",
"buId": "DEFAULT",
}];
var getAllSelected = function() {
var selecteddetails = $scope.details.filter(function(detail) {
return detail.Selected;
});
return selecteddetails.length === $scope.details.length;
}
var setAllSelected = function(value) {
angular.forEach($scope.details, function(detail) {
detail.Selected = value;
});
}
$scope.allSelected = function(value) {
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}
$scope.checkAll = function(Count) {
angular.forEach($scope.details, function(details) {
details.Selected = false;
});
};
});
i have updated your fiddle please check and review.http://jsfiddle.net/8MVLJ/2652/
it's not pushing it's value because you have pass scope in your modal controller and set parent scope like this
ModalService.showModal({
templateUrl: 'modal.html',
controller: "Controller",
scope:$scope <-- added here scope
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {});
});
and add $parent to push your value like this
$scope.$parent.newDetails.push({ <-- added $parent here
'attrName': detail.attrName,
'userAttrValue': detail.user_attr_value
});

After injecting $http, code is not displaying the table in angular.js

I am a beginner in anular.js. I'm trying to write a code which add and removes rows in a table on button click and once done ad user clicks on createdelivery button I want to send the data as a JSON object to server.
But when am injecting $http as follows,
var app = angular.module("createDelivery", []);
app.controller("MyController", ['$scope', 'http', function($scope, $http)
it doesn't create the table also.
Please help me to solve the issue.
<html>
<head>
<title>Add Rows</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module("createDelivery", []);
app.controller("MyController", ['$scope', 'http', function($scope, $http) {
$scope.deliveryDetails = [
{
'fname':'Muhammed',
'lname':'Shanid',
'email':'shanid#shanid.com'
},
{
'fname':'Roy',
'lname':'Mathew',
'email':'roy#roy.com'
}];
$scope.addNew = function(cdDetails){
$scope.deliveryDetails.push({
'fname': "",
'lname': "",
'email': "",
});
};
$scope.remove = function(){
var newDataList=[];
$scope.selectedAll = false;
angular.forEach($scope.deliveryDetails, function(selected){
if(!selected.selected){
newDataList.push(selected);
}
});
$scope.deliveryDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.deliveryDetails, function(cdDetails) {
cdDetails.selected = $scope.selectedAll;
});
};
$scope.getData = function(cdDetails)
{
alert("Check");
var jsonString;
jsonString = angular.toJson(cdDetails);
//JSON.stringify(jsonString);
$http
({
url: "/scheduler/createDelivery",
dataType: 'json',
method: 'POST',
data: jsonString
}).success(function(response) {
alert("success : : "+jsonString);
$scope.value = response;
}).error(function(error) {
alert("error::"+error);
});
//window.location.reload();
//document.write("\nString value "+jsonString);
};
}]);
</script>
</head>
<body ng-app="createDelivery" ng-controller="MyController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form ng-submit="addNew()">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" /></th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cdDetails in deliveryDetails">
<td>
<input type="checkbox" ng-model="cdDetails.selected"/></td>
<td>
<input type="text" class="form-control" ng-model="cdDetails.fname" required/></td>
<td>
<input type="text" class="form-control" ng-model="cdDetails.lname" required/></td>
<td>
<input type="email" class="form-control" ng-model="cdDetails.email" required/></td>
</tr>
</tbody>
</table>
<div class="form-group">
<input ng-hide="!deliveryDetails.length" type="button" class="btn btn-danger pull-right" ng-click="remove()" value="Remove">
<input type="submit" class="btn btn-primary addnew pull-right" value="Add New">
<button type="button" name = "createDelivery"class="col-sm-2 btn btn-primary" style="width:25%" ng-click="getData(cdDetails);">Create Delivery</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
app.controller("MyController", ['$scope', 'http'
One mistake in code is above. Change it and try. you must inject $http

Is it possible to fire ng-click of a button element from a button in another controller?

I want to use angular modal for CRUD operation, so for firing the modal we have button by id modalFire in ng-controller="ModalDemoCtrl" , this is my modal:
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">....</h3>
</div>
<div class="modal-body">
<form id="productForm" novalidate>
<div>
<label for="ProductName"> productName :</label>
<input type="text" name="ProductName" id="ProductName" ng-model="model.ProductName" value="" required />
</div>
<div style="margin:10px">
<label for="Price">price :</label>
<input type="text" name="Price" id="Price" ng-model="model.Price" />
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="Save()" ng-disabled="productForm.$invalid">save</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
<button type="button" id="modalFire" class="btn btn-default modalBtn" ng-click="open()">UpdateProduct</button>
</div>
and it's controller:
App.controller('ModalDemoCtrl', function ($scope, $modal) {
$scope.open = function (size) {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
};
});
App.controller('ModalInstanceCtrl', function ($scope, $modalInstance, $http) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
and i have a grid that shows ProductList :
<div ng-controller="ProductController" ng-init="GetAllProducts()">
<div class="row" style="margin-top:90px" ng-show="!ShowGrid">
<article class="widget">
<header class="widget__header">
<div class="widget__title">
<i class="pe-7s-menu"></i><h3>ProductList</h3>
</div>
<div class="widget__config">
<i class="pe-7f-refresh"></i>
<i class="pe-7s-close"></i>
</div>
</header>
<div class="widget__content table-responsive">
<table class="table table-striped media-table">
<thead style="background-color:rgba(33, 25, 36,0.1)">
<tr>
<th style="width:30%">price</th>
<th style="width:30%">productName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in Products">
<td>{{product.Price}}</td>
<td>{{product.ProductName}}</td>
</tr>
</tbody>
</table>
</div>
</article>
</div>
</div>
so, i want a way to add a button or <a> element for each row in grid that can fire the modal, is there any way?
Unless I misunderstand your question, why not just add the button to your ng-repeat in your table. For example:
<table class="table table-striped media-table">
<thead style="background-color:rgba(33, 25, 36,0.1)">
<tr>
<th>Price</th>
<th>ProductName</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in Products">
<td>{{product.Price}}</td>
<td>{{product.ProductName}}</td>
<td><button ng-click="loadItem(product)>Edit</button></td>
</tr>
</tbody>
</table>
Then inside your controller, just pass the product into your modal load function. For example:
$scope.loadItem = function(product){
var modalInstance = $modal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
product: function () {
return product;
}
}
});
};
See how you can pass the product to the function, and then use resolve to pass the product into the modal. In your modal controller you would attach the product to the $scope, and use it as you would any other view.

how to popup window using angularjs

I want a dialog comes up on a button click and ask for two dates to enter and give me days difference back on my page on a label using angularjs. Can anyone help me on this?
This is an excellent solution for Bootstrap 3, Angular UI and Modal dialogs.
http://codepen.io/m-e-conroy/pen/ALsdF
I tried using #user3360944 example and it works for me, How can I select multiple items from the popup and add it to a table on the parent page? Here is my code
Parent Template : Mainpage.html
<div ng-controller="ItemCtrl" class="modal-body">
<button class="btn btn-default" ng-click="open();">Open Dialog</button>
<div ng-show="selected">{{ selected.Name}}</div>
</div>
Popup Template : ItemSelectDlg.html
<table class="table table-hover grid">
<thead class="tableheader">
<tr>
<th>Name</th>
<th>Type</th>
<th>Payment</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items" ng-click="selected.item = item">
<td>{{item.Name}}</td>
<td>{{item.Type}}</td>
<td>{{item.Payment}}</td>
</tr>
</tbody>
</table>
Selected:
<b>{{ selected.item.Name }} </b>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
Script code :ItemCtrl
$scope.items = $scope.ProductSet[0].Items;
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl:'ItemSelectDlg.html',
controller: ModalInstanceCtrl,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
//cancel
});
};
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};

Resources