I'm looking to build an book shelf application which add, removes, edits books shelf data using angular routing.
But when I try to prepopulate a record to edit it, I'm not able to get the prepopulated values.
I have tried to assign value using $scope.{model name}. but it is not working
App.js
var myApp = angular.module('myApp', []);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/viewBook',
{ template : '<div ng-controller="ViewBookController"> <h2>Books</h2> <table class="table table-bordered table-condensed"> <thead> <tr> <td>Name</td> <td>Category</td> <td>Price</td> <td>Actions</td> </tr> </thead> <tr ng-repeat ="book in books"> <td>{{book.name}}</td> <td>{{book.category}}</td> <td>{{book.price}}</td> <td><span class="glyphicon glyphicon-edit">Edit</span> | <span class="glyphicon glyphicon-trash">Delete</span> </td> </tr> </table> </div>',
controller : 'ViewBookController'}).
when('/addBook',
{ template : '<div ng-controller = "ViewBookController"> <form class="well"> <label>Name*</label> <input type="text" name="name" ng-model="addBook.name" /><br/> <label>Category*</label> <input type="text" name="email" ng-model="addBook.category" /><br/> <label>Price*</label> <input type="text" name="phone" ng-model="addBook.price" /><br/> <br/> <input type="hidden" ng-model="addBook.id"/> <button ng-click ="add(addBook)">Add </button> <button type="button" class="btn btn-danger"><a href="#/viewBook">Cancel</button> </form> </div> ',
controller : 'ViewBookController'}).
otherwise({redirectTo: '/viewBook'});
}]);
myApp.controller('ViewBookController', function($scope, ViewBookService) {
$scope.tempbook ="";
$scope.books = ViewBookService.list();
$scope.delete = function (id) {
ViewBookService.delete(id);
// if ($scope.addBook.id == id)
// $scope.addBook = {};
}
$scope.add = function() {
ViewBookService.save($scope.addBook);
$scope.addBook = {};
alert('book added successfully');
}
$scope.edit = function (addBook,id) {
//$scope.addbook = $scope.tempbook;
$scope.addBook= (angular.copy(ViewBookService.get(id)));
}
});
myApp.service('ViewBookService', function() {
//to create unique book id
var uid = 3;
//books array to hold list of all books
var books = [{
id : 0,
name : 'Java',
category : 'software',
price : 600,
},
{
id : 1,
name : 'Sherlock Holmes',
category : 'fiction',
price : 350,
},
{
id : 2,
name : 'Wings of Fire',
category : 'autobiography',
price : 250,
}];
//save method create a new book if doesnt exist else update the existing object
this.save = function(book) {
if(book.id == null) {
book.id =uid++;
books.push(book)
}
else {
for(i in books) {
if(books[i].id == book.id) {
books[i] ==book;
}
}
}
}
//simply search books list for given id and returns the book object if found
this.get = function(id) {
for(i in books) {
if( books[i].id == id) {
return books[i];
}
}
}
//iterate through books list and delete book if found
this.delete = function (id) {
for (i in books) {
if (books[i].id == id) {
books.splice(i, 1);
}
}
}
//simply returns the books list
this.list = function () {
return books;
}
});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
</body>
</html>
Related
I've been wanted to delete the row by its id.
I've already done "things" in Service, Controller, Listfiles, and the Delete file.
This is the controller
#RequestMapping("/hapussertifikasi")
public String hapussertifikasi() {
return ("sertifikasi/hapussertifikasi");
}
#ResponseBody
#RequestMapping(value = "/hapussertifikasi/{angka}", method = RequestMethod.DELETE)
public Map<String, String> hapussertifikasi(#PathVariable("angka") Long angka, Model model) {
sertifikasisr.hapus(angka);
// key value
Map<String, String> map = new HashMap<>();
// pakai String string karena value key dan value nya string
System.out.println();
System.out.println(angka);
map.put("status", "berhasil");
// DARI BARANG SERVICE
/*
* if(brngsr.hapus(angka)) { // key value map.put("status", "berhasil"); }else {
* map.put("status", "gagal"); }
*/
return map;
}
This is the Service file
public boolean hapus(Long id) {
try {
sertifikasi.deleteById(id);
return true;
}catch(Exception e) {
return false;
}
}
This is the List File
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<!-- Nulis table didalam body -->
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<td>ID</td>
<td>Nama Sertifikasi</td>
<td>Penerbit</td>
<td>Masa Berlaku</td>
<td>#</td>
</tr>
</thead>
<tbody id="idTbodySertifikasi">
<tr th:each="item :${keysertifikasi}">
<td th:text="${item.id}">ID</td>
<td th:text="${item.certificate_name}">NamaBarang</td>
<td th:text="${item.publisher}">JenisBarang</td>
<td th:text="${item.until_year + '-' + item.until_month }">Sampai</td>
<td>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button"
data-toggle="dropdown">
More <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li class="clDropdown" data-value="0">Ubah</li>
<li class="clDropdown" data-value="1">Hapus</li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$('.table-responsive').on('show.bs.dropdown', function() {
$('.table-responsive').css("overflow", "inherit");
});
$('.table-responsive').on('hide.bs.dropdown', function() {
$('.table-responsive').css("overflow", "auto");
});
$(".clDropdown").click(function() {
debugger;
var x = $(this).data('value');
var angka = $(this).attr('data-idbarang');
if (x == 0) {
$.ajax({
url : './ubahsertifikasi',
method : 'Get',
success : function(model) {
debugger;
/* jahit model return dari controller ke body modal */
$('#idMdlBodyUbahSertifikasi').html(model);
/* pop up modalnya */
$('#idMdlUbahSertifikasi').modal('show');
},
error : function(model) {
debugger;
}
});
} else if (x == 1) {
debugger;
$.ajax({
url : './hapussertifikasi',
method : 'Get',
success : function(model) {
debugger;
/* jahit model return dari controller ke body modal */
$('#idMdlBodyHapusSertifikasi').html(model);
/* pop up modalnya */
$('#idMdlHapusSertifikasi').modal('show');
},
error : function(model) {
debugger;
}
});
}
});
</script>
</body>
</html>
And lastly this is the delete file where the delete button is placed
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="col-xs-12">
<div class="row">
<div class="col-xs-2">
<i class="glyphicon glyphicon-trash center" style="font-size: 50px"></i>
</div>
<div class="col-xs-8">
<div class="clTulisanHapus center" id="idTulisanHapus">Anda
Yakin ingin menghapus Pelatihan?</div>
</div>
</div>
</div>
<div class="col-md-offset-8">
<div class="btn-group">
<button type="button" id="idBtnHapusBatal" class="btn clBtnMdlHapus">Tidak</button>
<button type="button" id="idBtnHapusHapus" class="btn clBtnMdlHapus">Ya</button>
</div>
</div>
<script>
$('#idBtnHapusHapus').click(function() {
var angka = $(this).attr('data-id');
debugger;
debugger;
$.ajax({
url : '/hapussertifikasi/' + angka,
type : 'DELETE',
success : function(model) {
debugger;
window.location = './sertifikasi'
},
error : function(model) {
debugger;
}
});
});
</script>
</body>
</html>
The id is showing ok, but the id values isn't sending to the Controller file.
The button <button type="button" id="idBtnHapusHapus" class="btn clBtnMdlHapus">Ya</button> has no data-id attribute, thus when calling var angka = $(this).attr('data-id');, angka is Nil.
This means you are making a delete request on /hapussertifikasi/, which is going to return a 400 error because you aren't passing the required argument (correct syntax would be /hapussertifikasi/14 where 14 is the id you want to delete.)
hi bro i also face this type of problem .....
after longtime R&D i found a solution , but i don't know why it's working..
try this
url : 'hapussertifikasi/' + angka,
just remove first /sing
I am working on angularjs routing where i have an array of employees in factory and the homecontroller displays those arrays in the view and view to html page (please correct me if my sequence or construction is wrong). I do edit and add employee operation on them . While doing edit operation , as soon as i click on the edit link, it routes to edit.html page and the view is controlled by EditController. However, i want the text boxes to contain and retain there original values, like empId:1, empName:John, empLocation:Mumbai when in edit.html page, but all the values doesn't come . Please help.
app.js
angular.module("Swabhav.Employee",['ngRoute'])
.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/',{
controller:"HomeController",
templateUrl:"home.html"
})
.when('/add',{
controller:"AddController",
templateUrl:"add.html"
})
.when('/home',{
controller:"HomeController",
templateUrl:"home.html"
})
.when('/edit/:empId',{
controller:"EditController",
templateUrl:"edit.html"
})
}])
EmployeeService Factory
angular.module("Swabhav.Employee")
.factory("EmployeeService",["$log",function($log){
var employees=[{"empId":1,"name":"John","location":"Mumbai"},
{"empId":2,"name":"Nikita","location":"Mumbai"},
{"empId":3,"name":"Saurab","location":"Pune"},
{"empId":4,"name":"Ankita","location":"Bangalore"},
{"empId":5,"name":"Harsh","location":"Chennai"},
{"empId":6, "name":"Geeta","location":"Vellore"}];
var obj={};
obj.displayAll=function(){
return employees;
}
obj.getById = function(Id){
var employee=[];
$log.log("emp id = "+ Id)
angular.forEach(employees,function(value,key){
if(value.empId==Id){
$log.log("inside");
$log.log(employees);
$log.log(value.location)
employee.push({empId:value.empId,name:value.name,location:value.location});
$log.log(employee)
}
return (employee);
})
}
obj.addEmployee=function(Id,Name,Location){
$log.log(employees)
employees.push({empId:Id,name:Name,location:Location})
return employees;
}
obj.editEmployee=function(employeeId,employeeName,employeeLocation){
var index;
for(index=0;index<employees.length;index++){
if(employees.indexOf(employeeId) != -1){
$log.log("edit employee = "+ employees[index])
employees.empId=employeeId;
employees.name=employeeName;
employees.location=employeeLocation;
}
}
return employees;
}
return obj;
}])
HomeController
angular.module("Swabhav.Employee")
.controller("HomeController",
["$scope","EmployeeService","$log","$window",function($scope,
EmployeeService,$log,$window){
$log.log (EmployeeService.displayAll());
$scope.data=EmployeeService.displayAll();
}])
AddController
angular.module("Swabhav.Employee")
.controller("AddController",
["$scope","EmployeeService","$log","$window",function($scope,
EmployeeService,$log,$window){
$scope.add=function(empId,name,location){
$scope.Id=empId;
$scope.Name=name;
$scope.Location=location
EmployeeService.addEmployee($scope.Id,$scope.Name,$scope.Location);
$window.location.href = "#/home";
}
}])
EditController
angular.module("Swabhav.Employee")
.controller("EditController",
["$scope","EmployeeService","$log","$window","$routeParams",
function($scope,EmployeeService,$log,$window,$routeParams){
$scope.employeeData=EmployeeService.displayAll();
$log.log("$scope.employeeData = "+ $routeParams.empId )
$scope.empIdvalue = $routeParams.empId;
$scope.editDisplay=
EmployeeService.getById($scope.empIdvalue);
$log.log("EmployeeService.getById(3)"+EmployeeService.getById(3));
$scope.edit= function(empId,name,location){
$scope.Id=empId;
$scope.Name=name;
$scope.Location=location
EmployeeService.editEmployee($scope.Id,$scope.Name,$scope.Location);
$window.location.href = "#/home";
}
}])
home.html
<article>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Location</th>
<th> Edit </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in data" >
<td>{{employee.empId}} </td>
<td>{{employee.name}} </td>
<td>{{employee.location}}</td>
<td>Edit
</td>
</tr>
</tbody>
<br>
Add Employee
</table>
</article>
edit.html
<article>
<h3>Edit Page</h3>
<br><br>
empId:<input type="text" ng-value=empIdvalue ng-model="employeeId">
empName:<input type="text" ng-value=empNamevalue ng-model="employeeName">
empLocation:<input type="text" ng-value=empLocationvalue ng-
model="employeeLocation">
<button type="button" ng-
click="edit(employeeId,employeeName,employeeLocation)">Edit</button>
</article>
index.html
<html ng-app="Swabhav.Employee">
<head>
<title>Employee</title>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
<script src="app.js"></script>
<section ng-view></section>
</body>
</html>
You should not use ng-value. You can use the $scope.editDisplay variable as model. You can change your code like this.
edit.html
<article>
<h3>Edit Page</h3>
<br><br>
empId:<input type="text" ng-model="editDisplay.empId">
empName:<input type="text" ng-model="editDisplay.name">
empLocation:<input type="text" ng-model="editDisplay.location">
<button type="button" ng-
click="edit(editDisplay)">Edit</button>
</article>
EditController
angular.module("Swabhav.Employee")
.controller("EditController",
["$scope","EmployeeService","$log","$window","$routeParams",
function($scope,EmployeeService,$log,$window,$routeParams){
$scope.employeeData=EmployeeService.displayAll();
$log.log("$scope.employeeData = "+ $routeParams.empId )
$scope.empIdvalue = $routeParams.empId;
$scope.editDisplay=
EmployeeService.getById($scope.empIdvalue);
$log.log("EmployeeService.getById(3)"+EmployeeService.getById(3));
$scope.edit= function(editDisplay){
EmployeeService.editEmployee(editDisplay.empId,editDisplay.name,editDisplay.location);
$window.location.href = "#/home";
}
}])
You need to change you editcontroller like this:
angular.module("Swabhav.Employee")
.controller("EditController",
["$scope","EmployeeService","$log","$window","$routeParams",
function($scope,EmployeeService,$log,$window,$routeParams){
$scope.param1 = $routeParams.empId;
$scope.employeeData=EmployeeService.displayAll();
$scope.empIdvalue = $routeParams.empId;
$scope.editDisplay=
EmployeeService.getById($scope.empIdvalue);
$scope.param2 = $scope.editDisplay[0]["location"];
$scope.param3 = $scope.editDisplay[0]["name"];
$scope.edit= function(empId,name,location){
$scope.Id=empId;
$scope.Name=name;
$scope.Location=location;
EmployeeService.editEmployee($scope.Id,$scope.Name,$scope.Location);
$window.location.href = "#/home";
}
}])
param1 param2 and param3, will be used in your ng-model in edit.html.
<article>
<h3>Edit Page</h3>
<br><br>
empId:<input type="text" disabled="disabled" ng-model="param1">
empName:<input type="text" ng-value="editDisplay[0]['name']" ng-model="param2">
empLocation:<input type="text" ng-value="editDisplay[0]['location']" ng-model="param3">
<button type="button" ng-click="edit(editDisplay[0]['empId'],param2,param3)">Edit</button>
</article>
return
Another error you have comitted in getById function, thinking that foreach promises return a value to the container parent function, no it just throws back to the nearer promise, it is rather adviced to use a filter selector like this:
obj.getById = function(Id){
return employees.filter(function(value,key){
if(value.empId==Id)
return 1;
else
return 0;
})
}
Finally there is another substiantial change in editEmployee function, you seem to jumble it a whole.
obj.editEmployee=function(employeeId,employeeName,employeeLocation){
var index=employees.map((id)=>id.empId).indexOf(employeeId);
if(index != -1){
$log.log("edit employee = "+ employees.map((id)=>id.name)[index])
employees[index].empId=employeeId;
employees[index].name=employeeName;
employees[index].location=employeeLocation;
}
return employees;
}
forked here
row add using angular code. Input box model name is "code". when click this input box a model open and when any row select using angularjs then there is a problem when I assign value using $scope.code it will assign to all input box in but I want to assign that value by which ng-click performed.
<table class="table table-bordered table-hover table-condensed">
<tr style="font-weight: bold">
<td style="width:35%">Code</td>
</tr>
<tr ng-repeat="user in users">
<td>
<!-- editable username (text with validation) -->
<span ng-show="editDel">
#{{ user.name || 'empty' }}
</span>
#{{code}}
<input type="text" name="" ng-model="code" ng-show="saveCancel" ng-click="getCode()">
</td>
<td style="white-space: nowrap">
<!-- form -->
<form ng-show="saveCancel" class="form-buttons form-inline">
<button type="submit" class="btn btn-primary">
save
</button>
<button type="button" ng-click="isCancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="editDel">
<button class="btn btn-primary" ng-click="editUser($index)">edit</button>
<button class="btn btn-danger" ng-click="removeUser($index)">del</button>
</div>
</td>
</tr>
</table>
$scope.users = [];
$scope.saveCancel = false;
$scope.editDel = true;
$scope.saveUser = function(data, id) {
//$scope.user not updated yet
angular.extend(data, {id: id});
return $http.post('/saveUser', data);
};
// remove user
$scope.removeUser = function(index) {
$scope.users.splice(index, 1);
};
// add user add row
$scope.addUser = function() {
$scope.inserted = {
id: $scope.users.length+1,
name: '',
status: null,
group: null
};
// $scope.taxNamePopup();
$scope.users.push($scope.inserted);
};
$scope.getCode = function(){
// alert(input_id);
this.code = 'nameValue';//**this assin value to selected box**
// jQuery("#tax_modal").modal("hide");
var request = $http({
method: "get",
url: base_url+"/load-tax",
data: {
},
}).then(function successCallback(response) {
jQuery("#tax_list").modal("show");
$scope.tax_data1 = response;
}, function errorCallback(response) {
});
}
$scope.getSelected = function(id,code,desc,rate){
alert(code);
this.code = code;//**but i want to assign value to selected input box from here**
jQuery("#tax_list").modal("hide");
}
$scope.safeApply(function() {
$scope.editUser = function($id){
this.saveCancel = true;
this.editDel = false;
}
});
$scope.isCancel = function(){
this.saveCancel = false;
this.editDel = true;
}
it is because ng-model is codefor every input.
Change it with following code example
<input type="text" name="" ng-model="code_$index" ng-show="saveCancel" ng-click="getCode($index)">
Now above code will change the ng-model unique for each input field and retrieve the value in getCode on the basis of index.
the model should be different for each ng-repeat item
EDIT change from getCode(user.code) to getCode(user)
<input type="text" name="" ng-model="user.code" ng-show="saveCancel" ng-click="getCode(user)">
use the param how ever you want ;)
$scope.getCode = function(user){
angular.forEach($scope.users, function (value, key) {
if (value.id == user.id) {
$scope.users[key]=user;
}
});
}
**Hi,i am filtering the array data from textbox but the code is not working properly can any one help me please.the data from back end
self.AdminLineDetails = function(data) {
$scope.details = [];
$scope.details = data.GoalData;
console.log(data);
}
<div class="row">
<div class="col-md-12">
<input ng-model="query" type="text" class="form-control" placeholder="Filter by name or number">
</div>
<div>
<tbody>
<tr ng-repeat="detail in details|filter:query">
<td>{{detail.firstName}}
</td>
<td>{{detail.lastName}}
</td>
<td>{{detail.mdn}}
</td>
</tr>
</tbody>
</div>
**
You can specify on which property you are trying to filter, do something like
<tr ng-repeat="detail in details|filter: {firstName: query}">
<input type="text" ng-model="search">
<ul ng-repeat="oneauth in authorisations[0]">
<li ng-repeat="entry in oneauth | nameFilter:search">{{entry.auth.name}}</li>
</ul>
JS
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.authorisations = [{
"authorisations":[
{
"auth":{
"number":"453",
"name":"Apple Inc."
}
},
{
"auth":{
"number":"123",
"name":"Microsoft Inc."
}
}]
}];
});
app.filter('nameFilter', function(){
return function(objects, criteria){
var filterResult = new Array();
if(!criteria)
return objects;
for(index in objects) {
if(objects[index].auth.name.indexOf(criteria) != -1) // filter by name only
filterResult.push(objects[index]);
}
console.log(filterResult);
return filterResult;
}
});
Check this sample
http://jsfiddle.net/yctchgnk/
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Batch editable table</title>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
<link rel='stylesheet prefetch' href='https://cdn.rawgit.com/esvit/ng-table/v0.8.1/dist/ng-table.min.css'>
<link rel='stylesheet prefetch' href='css/nqjzro.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div ng-app="myApp" class="container-fluid">
<div class="row">
<div class="col-xs-12">
<h2 class="page-header">Batch editable table</h2>
<div class="row">
<div class="col-md-6">
<div class="bs-callout bs-callout-info">
<h4>Overview</h4>
<p>Example of how to create a batch editable table.</p>
</div>
</div>
<div class="col-md-6">
<div class="bs-callout bs-callout-warning">
<h4>Notice</h4>
<p>There are several directives in use that track dirty state and validity of the table rows. Whilst they are reasonally capable they are <em>not production tested - use at your own risk!</em> More details...</p>
<div ng-show="isExplanationOpen">
<p>If you look at the declarative markup for the <code>ngTable</code> you'll see a bunch of nested <code>ngForm</code> directives, with a common ancestor <code>ngForm</code> at the level of the table element. Each nested <code>ngForm</code> propogates their <code>$dirty</code> and <code>$invalid</code> state to this top level <code>ngForm</code>. This works great as you can enable/disable the buttons for saving the table based on the status of this single top-level <code>ngForm</code>.</p>
<p>This works up till the point that the user select's a new page to display in the table. At which point the existing nested <code>ngForm</code> directives are swapped out for new instances as the new data page is loaded. These new <code>ngForm</code> directives are always pristine and valid and this status propogates setting the corrosponding state on the top-level to be pristine and valid even though rows from the previous page are dirty and possibly invalid.</p>
<p>The solution is to have a set of directives that sit parallel to the <code>ngForm</code> directives that remember the state of the rows when the corrosponding <code>ngFrom</code> directives are destroyed and recreated. When <code>ngForm</code> directives are recreated they have their status reset by the directives that have remembered this state.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6" ng-controller="demoController as demo">
<h3>ngTable directive</h3>
<div class="brn-group pull-right">
<button class="btn btn-default" ng-if="demo.isEditing" ng-click="demo.cancelChanges()">
<span class="glyphicon glyphicon-remove"></span>
</button>
<button class="btn btn-primary" ng-if="!demo.isEditing" ng-click="demo.isEditing = true">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-primary" ng-if="demo.isEditing" ng-disabled="!demo.hasChanges() || demo.tableTracker.$invalid" ng-click="demo.saveChanges()">
<span class="glyphicon glyphicon-ok"></span>
</button>
<button class="btn btn-default" ng-click="demo.add()">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<table ng-table="demo.tableParams" class="table table-bordered table-hover table-condensed editable-table" ng-form="demo.tableForm" disable-filter="demo.isAdding" demo-tracked-table="demo.tableTracker">
<colgroup>
<col width="70%" />
<col width="12%" />
<col width="13%" />
<col width="5%" />
</colgroup>
<tr ng-repeat="row in $data" ng-form="rowForm" demo-tracked-table-row="row">
<td title="'Name'" filter="{name: 'text'}" sortable="'name'" ng-switch="demo.isEditing" ng-class="name.$dirty ? 'bg-warning' : ''" ng-form="name" demo-tracked-table-cell>
<span ng-switch-default class="editable-text">{{row.name}}</span>
<div class="controls" ng-class="name.$invalid && name.$dirty ? 'has-error' : ''" ng-switch-when="true">
<input type="text" name="name" ng-model="row.name" class="editable-input form-control input-sm" required />
</div>
</td>
<td title="'Age'" filter="{age: 'number'}" sortable="'age'" ng-switch="demo.isEditing" ng-class="age.$dirty ? 'bg-warning' : ''" ng-form="age" demo-tracked-table-cell>
<span ng-switch-default class="editable-text">{{row.age}}</span>
<div class="controls" ng-class="age.$invalid && age.$dirty ? 'has-error' : ''" ng-switch-when="true">
<input type="number" name="age" ng-model="row.age" class="editable-input form-control input-sm" required/>
</div>
</td>
<td title="'Money'" filter="{money: 'number'}" sortable="'money'" ng-switch="demo.isEditing" ng-class="money.$dirty ? 'bg-warning' : ''" ng-form="money" demo-tracked-table-cell>
<span ng-switch-default class="editable-text">{{row.money}}</span>
<div class="controls" ng-class="money.$invalid && money.$dirty ? 'has-error' : ''" ng-switch-when="true">
<input type="number" name="money" ng-model="row.money" class="editable-input form-control input-sm" required/>
</div>
</td>
<td>
<button class="btn btn-danger btn-sm" ng-click="demo.del(row)" ng-disabled="!demo.isEditing"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
</table>
</div>
<div class="col-md-6" ng-controller="dynamicDemoController as demo">
<h3>ngTableDynamic directive</h3>
<div class="brn-group pull-right">
<button class="btn btn-default" ng-if="demo.isEditing" ng-click="demo.cancelChanges()">
<span class="glyphicon glyphicon-remove"></span>
</button>
<button class="btn btn-primary" ng-if="!demo.isEditing" ng-click="demo.isEditing = true">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<button class="btn btn-primary" ng-if="demo.isEditing" ng-disabled="!demo.hasChanges() || demo.tableTracker.$invalid" ng-click="demo.saveChanges()">
<span class="glyphicon glyphicon-ok"></span>
</button>
<button class="btn btn-default" ng-click="demo.add()">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<table ng-table-dynamic="demo.tableParams with demo.cols" class="table table-bordered table-condensed table-hover editable-table" ng-form="demo.tableForm" disable-filter="demo.isAdding" demo-tracked-table="demo.tableTracker">
<colgroup>
<col width="70%" />
<col width="12%" />
<col width="13%" />
<col width="5%" />
</colgroup>
<tr ng-repeat="row in $data" ng-form="rowForm" demo-tracked-table-row="row">
<td ng-repeat="col in $columns" ng-class="rowForm[col.field].$dirty ? 'bg-warning' : ''" ng-form="{{col.field}}" demo-tracked-table-cell>
<span ng-if="col.dataType !== 'command' && !demo.isEditing" class="editable-text">{{row[col.field]}}</span>
<div ng-if="col.dataType !== 'command' && demo.isEditing" class="controls" ng-class="rowForm[col.field].$invalid && rowForm[col.field].$dirty ? 'has-error' : ''" ng-switch="col.dataType">
<input ng-switch-default type="text" name="{{col.field}}" ng-model="row[col.field]" class="editable-input form-control input-sm" required />
<input ng-switch-when="number" type="number" name="{{col.field}}" ng-model="row[col.field]" class="editable-input form-control input-sm" required />
</div>
<button ng-if="col.dataType === 'command'" class="btn btn-danger btn-sm" ng-click="demo.del(row)" ng-disabled="!demo.isEditing"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
</table>
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js'></script>
<script src='https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js'></script>
<script src="js/index.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular-route.js"></script>
</body>
</html>
The above is html code
angular.module("myApp", ["ngTable", "ngTableDemos"]);
(function() {
"use strict";
angular.module("myApp").controller("demoController", demoController);
demoController.$inject = ["NgTableParams", "ngTableSimpleList"];
function demoController(NgTableParams, simpleList) {
var self = this;
var originalData = angular.copy(simpleList);
self.tableParams = new NgTableParams({}, {
dataset: angular.copy(simpleList)
});
self.deleteCount = 0;
self.add = add;
self.cancelChanges = cancelChanges;
self.del = del;
self.hasChanges = hasChanges;
self.saveChanges = saveChanges;
//////////
function add() {
self.isEditing = true;
self.isAdding = true;
self.tableParams.settings().dataset.unshift({
name: "",
age: null,
money: null
});
// we need to ensure the user sees the new row we've just added.
// it seems a poor but reliable choice to remove sorting and move them to the first page
// where we know that our new item was added to
self.tableParams.sorting({});
self.tableParams.page(1);
self.tableParams.reload();
}
function cancelChanges() {
resetTableStatus();
var currentPage = self.tableParams.page();
self.tableParams.settings({
dataset: angular.copy(originalData)
});
// keep the user on the current page when we can
if (!self.isAdding) {
self.tableParams.page(currentPage);
}
}
function del(row) {
_.remove(self.tableParams.settings().dataset, function(item) {
return row === item;
});
self.deleteCount++;
self.tableTracker.untrack(row);
self.tableParams.reload().then(function(data) {
if (data.length === 0 && self.tableParams.total() > 0) {
self.tableParams.page(self.tableParams.page() - 1);
self.tableParams.reload();
}
});
}
function hasChanges() {
return self.tableForm.$dirty || self.deleteCount > 0
}
function resetTableStatus() {
self.isEditing = false;
self.isAdding = false;
self.deleteCount = 0;
self.tableTracker.reset();
self.tableForm.$setPristine();
}
function saveChanges() {
resetTableStatus();
var currentPage = self.tableParams.page();
originalData = angular.copy(self.tableParams.settings().dataset);
}
}
})();
(function() {
"use strict";
angular.module("myApp").controller("dynamicDemoController", dynamicDemoController);
dynamicDemoController.$inject = ["NgTableParams", "ngTableSimpleList"];
function dynamicDemoController(NgTableParams, simpleList) {
var self = this;
var originalData = angular.copy(simpleList);
self.cols = [{
field: "name",
title: "Name",
filter: {
name: "text"
},
sortable: "name",
dataType: "text"
}, {
field: "age",
title: "Age",
filter: {
age: "number"
},
sortable: "age",
dataType: "number"
}, {
field: "money",
title: "Money",
filter: {
money: "number"
},
sortable: "money",
dataType: "number"
}, {
field: "action",
title: "",
dataType: "command"
}];
self.tableParams = new NgTableParams({}, {
dataset: angular.copy(simpleList)
});
self.deleteCount = 0;
self.add = add;
self.cancelChanges = cancelChanges;
self.del = del;
self.hasChanges = hasChanges;
self.saveChanges = saveChanges;
//////////
function add() {
self.isEditing = true;
self.isAdding = true;
self.tableParams.settings().dataset.unshift({
name: "",
age: null,
money: null
});
// we need to ensure the user sees the new row we've just added.
// it seems a poor but reliable choice to remove sorting and move them to the first page
// where we know that our new item was added to
self.tableParams.sorting({});
self.tableParams.page(1);
self.tableParams.reload();
}
function cancelChanges() {
resetTableStatus();
var currentPage = self.tableParams.page();
self.tableParams.settings({
dataset: angular.copy(originalData)
});
// keep the user on the current page when we can
if (!self.isAdding) {
self.tableParams.page(currentPage);
}
}
function del(row) {
_.remove(self.tableParams.settings().dataset, function(item) {
return row === item;
});
self.deleteCount++;
self.tableTracker.untrack(row);
self.tableParams.reload().then(function(data) {
if (data.length === 0 && self.tableParams.total() > 0) {
self.tableParams.page(self.tableParams.page() - 1);
self.tableParams.reload();
}
});
}
function hasChanges() {
return self.tableForm.$dirty || self.deleteCount > 0
}
function resetTableStatus() {
self.isEditing = false;
self.isAdding = false;
self.deleteCount = 0;
self.tableTracker.reset();
self.tableForm.$setPristine();
}
function saveChanges() {
resetTableStatus();
var currentPage = self.tableParams.page();
originalData = angular.copy(self.tableParams.settings().dataset);
}
}
})();
(function() {
"use strict";
angular.module("myApp").run(configureDefaults);
configureDefaults.$inject = ["ngTableDefaults"];
function configureDefaults(ngTableDefaults) {
ngTableDefaults.params.count = 5;
ngTableDefaults.settings.counts = [];
}
})();
/**********
The following directives are necessary in order to track dirty state and validity of the rows
in the table as the user pages within the grid
------------------------
*/
(function() {
angular.module("myApp").directive("demoTrackedTable", demoTrackedTable);
demoTrackedTable.$inject = [];
function demoTrackedTable() {
return {
restrict: "A",
priority: -1,
require: "ngForm",
controller: demoTrackedTableController
};
}
demoTrackedTableController.$inject = ["$scope", "$parse", "$attrs", "$element"];
function demoTrackedTableController($scope, $parse, $attrs, $element) {
var self = this;
var tableForm = $element.controller("form");
var dirtyCellsByRow = [];
var invalidCellsByRow = [];
init();
////////
function init() {
var setter = $parse($attrs.demoTrackedTable).assign;
setter($scope, self);
$scope.$on("$destroy", function() {
setter(null);
});
self.reset = reset;
self.isCellDirty = isCellDirty;
self.setCellDirty = setCellDirty;
self.setCellInvalid = setCellInvalid;
self.untrack = untrack;
}
function getCellsForRow(row, cellsByRow) {
return _.find(cellsByRow, function(entry) {
return entry.row === row;
})
}
function isCellDirty(row, cell) {
var rowCells = getCellsForRow(row, dirtyCellsByRow);
return rowCells && rowCells.cells.indexOf(cell) !== -1;
}
function reset() {
dirtyCellsByRow = [];
invalidCellsByRow = [];
setInvalid(false);
}
function setCellDirty(row, cell, isDirty) {
setCellStatus(row, cell, isDirty, dirtyCellsByRow);
}
function setCellInvalid(row, cell, isInvalid) {
setCellStatus(row, cell, isInvalid, invalidCellsByRow);
setInvalid(invalidCellsByRow.length > 0);
}
function setCellStatus(row, cell, value, cellsByRow) {
var rowCells = getCellsForRow(row, cellsByRow);
if (!rowCells && !value) {
return;
}
if (value) {
if (!rowCells) {
rowCells = {
row: row,
cells: []
};
cellsByRow.push(rowCells);
}
if (rowCells.cells.indexOf(cell) === -1) {
rowCells.cells.push(cell);
}
} else {
_.remove(rowCells.cells, function(item) {
return cell === item;
});
if (rowCells.cells.length === 0) {
_.remove(cellsByRow, function(item) {
return rowCells === item;
});
}
}
}
function setInvalid(isInvalid) {
self.$invalid = isInvalid;
self.$valid = !isInvalid;
}
function untrack(row) {
_.remove(invalidCellsByRow, function(item) {
return item.row === row;
});
_.remove(dirtyCellsByRow, function(item) {
return item.row === row;
});
setInvalid(invalidCellsByRow.length > 0);
}
}
})();
(function() {
angular.module("myApp").directive("demoTrackedTableRow", demoTrackedTableRow);
demoTrackedTableRow.$inject = [];
function demoTrackedTableRow() {
return {
restrict: "A",
priority: -1,
require: ["^demoTrackedTable", "ngForm"],
controller: demoTrackedTableRowController
};
}
demoTrackedTableRowController.$inject = ["$attrs", "$element", "$parse", "$scope"];
function demoTrackedTableRowController($attrs, $element, $parse, $scope) {
var self = this;
var row = $parse($attrs.demoTrackedTableRow)($scope);
var rowFormCtrl = $element.controller("form");
var trackedTableCtrl = $element.controller("demoTrackedTable");
self.isCellDirty = isCellDirty;
self.setCellDirty = setCellDirty;
self.setCellInvalid = setCellInvalid;
function isCellDirty(cell) {
return trackedTableCtrl.isCellDirty(row, cell);
}
function setCellDirty(cell, isDirty) {
trackedTableCtrl.setCellDirty(row, cell, isDirty)
}
function setCellInvalid(cell, isInvalid) {
trackedTableCtrl.setCellInvalid(row, cell, isInvalid)
}
}
})();
(function() {
angular.module("myApp").directive("demoTrackedTableCell", demoTrackedTableCell);
demoTrackedTableCell.$inject = [];
function demoTrackedTableCell() {
return {
restrict: "A",
priority: -1,
scope: true,
require: ["^demoTrackedTableRow", "ngForm"],
controller: demoTrackedTableCellController
};
}
demoTrackedTableCellController.$inject = ["$attrs", "$element", "$scope"];
function demoTrackedTableCellController($attrs, $element, $scope) {
var self = this;
var cellFormCtrl = $element.controller("form");
var cellName = cellFormCtrl.$name;
var trackedTableRowCtrl = $element.controller("demoTrackedTableRow");
if (trackedTableRowCtrl.isCellDirty(cellName)) {
cellFormCtrl.$setDirty();
} else {
cellFormCtrl.$setPristine();
}
// note: we don't have to force setting validaty as angular will run validations
// when we page back to a row that contains invalid data
$scope.$watch(function() {
return cellFormCtrl.$dirty;
}, function(newValue, oldValue) {
if (newValue === oldValue) return;
trackedTableRowCtrl.setCellDirty(cellName, newValue);
});
$scope.$watch(function() {
return cellFormCtrl.$invalid;
}, function(newValue, oldValue) {
if (newValue === oldValue) return;
trackedTableRowCtrl.setCellInvalid(cellName, newValue);
});
}
})();
This is javascript file
The above code is angularjs. It displays table loading data with add row, delete, edit.
Please solve this. Am getting error [$injector:modulerr] . Please help me to solve
Edit: They created different codepen for ngTableDemos look here
To run your sample you need to load that ngTableDemos related code first then your sample.
For codepen, to understand what are the files they are using to run any sample check Pen Setting JavaScript tab carefully.
Probably you didn't load "ngTableDemos" module, so if it is needed load associate file or remove it like
angular.module("myApp", ["ngTable"]);