New record not insert in Table view - angularjs

Hi I am a beginner for Angular-Js and I am trying to show a table view and give facility to add New records, but the problem is when I am trying to add a new record data is not inserting and my code is below.
What mistake did I make?
Can some one help me please.
I followed below link for doing my requirement:
https://lorenzofox3.github.io/smart-table-website/
index.html:-
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css#3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js#1.2.21" data-semver="1.2.21" src="https://code.angularjs.org/1.2.21/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="smart-table.js"></script>
<script src="IrInfiniteScrollPlugin.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="safeCtrl">
<button type="button" ng-click="addRandomItem(row)" class="btn btn-sm btn-success">
<i class="glyphicon glyphicon-plus">
</i> Add random item
</button>
<table st-table="displayedCollection" st-safe-src="rowCollection" class="table table-striped">
<thead>
<tr>
<th st-sort="firstName">first name</th>
<th st-sort="lastName">last name</th>
<th st-sort="birthDate">birth date</th>
<th st-sort="balance">balance</th>
</tr>
<tr>
<th colspan="5"><input st-search="" class="form-control" placeholder="global search ..." type="text"/></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in displayedCollection">
<td>{{row.firstName}}</td>
<td>{{row.lastName}}</td>
<td>{{row.birthDate}}</td>
<td>{{row.balance}}</td>
<td>
<button type="button" ng-click="removeItem(row)" class="btn btn-sm btn-danger">
<i class="glyphicon glyphicon-remove-circle">
</i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
app.js:
angular.module('myApp', []).controller('safeCtrl', function($scope) {
var firstnames = ['Laurent', 'Blandine', 'Olivier', 'Max'];
var lastnames = ['Renard', 'Faivre', 'Frere', 'Eponge'];
var dates = ['1987-05-21', '1987-04-25', '1955-08-27', '1966-06-06'];
var id = 1;
function generateRandomItem(id) {
var firstname = firstnames[Math.floor(Math.random() * 3)];
var lastname = lastnames[Math.floor(Math.random() * 3)];
var birthdate = dates[Math.floor(Math.random() * 3)];
var balance = Math.floor(Math.random() * 2000);
return {
id: id,
firstName: firstname,
lastName: lastname,
birthDate: new Date(birthdate),
balance: balance
}
}
$scope.rowCollection = [];
for (id; id < 5; id++) {
$scope.rowCollection.push(generateRandomItem(id));
}
//add to the real data holder
$scope.addRandomItem = function addRandomItem() {
$scope.rowCollection.push(generateRandomItem(id));
id++;
};
//remove to the real data holder
$scope.removeItem = function removeItem(row) {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
}
});

You need to change your functions to:
//add to the real data holder
$scope.addRandomItem = function() {
$scope.rowCollection.push(generateRandomItem(id));
id++;
};
//remove to the real data holder
$scope.removeItem = function(row) {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
}
When you're declaring functions inside your scope using the syntax: $scope.functionName = function(), you don't need to write the functionName on the right after function().

Related

angular, select with dynamic disabled

Now I am trying to select box with disabled.
When $shop.products.product[i].productId is changed by selectBox, I want that value disabled in select box option.
for example, if i select 3 in select box on second row, then select box option 1,3 are disabled.
so i register $watch witch resync isDisabled field when $shop.products[i].productId is changed.
i don't know why $watch is no calling. help me please.
// Code goes here
angular.module("myApp")
.controller("myCtrl", function($scope) {
$scope.shop = {
"id" : 'shop1',
"products" : [
{"productId" : 1,"desc" : 'product1'},
{"productId" : 2,"desc" : 'product2'}
]
};
$scope.allSelectBoxItems = [
{"id" : 1, "isDisabled" : true},
{"id" : 2, "isDisabled" : true},
{"id" : 3, "isDisabled" : false},
{"id" : 4, "isDisabled" : false}
];
$scope.addWatcher = function(index){
console.log('register watcher to ' + index);
$scope.$watch('shop.product[' + index + '].productId', function(newValue, oldValue){
console.log('watcher envoked');
if (newValue != oldValue) {
var selected = $scope.shop.products.map(function (product) {
return product.productId;
});
for (var i = 0; i < $scope.allSelectBoxItems.length; i++) {
var isSelected = selected.includes($scope.allSelectBoxItems[i].productId);
console.log(isSelected);
$scope.allSelectBoxItems.isDisabled = isSelected;
}
}
});
}
angular.forEach($scope.shop.products, function(value, index){
$scope.addWatcher(index);
});
$scope.addProduct = function(){
var nextProductId = $scope.shop.products.length + 1;
var newProduct = {"productId" : nextProductId ,"desc" : 'product' + nextProductId};
$scope.shop.products.push(newProduct);
$scope.addWatcher(nextProductId - 1);
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-animate.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-touch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<script>
angular.module("myApp", ['ngAnimate', 'ui.bootstrap'])
</script>
<script src="script.js"></script>
</head>
<body ng-controller="myCtrl">
<div>
<table class="table">
<tbody>
<tr>
<th>id</th>
<td>{{shop.id}}</td>
</tr>
<tr>
<td>
products
<br>
<button type="button" class="btn btn-default" ng-click="addProduct()"><span class="glyphicon glyphicon-plus" aria-hidden="true" style="margin-right:4px"></span>add product</button>
</td>
<td>
<table class="table">
<tbody>
<tr>
<td>producId</td>
<td>desc</td>
</tr>
<tr ng-repeat="product in shop.products">
<td>
<select ng-model="product.productId" ng-options="selectBoxItem.id as selectBoxItem.id disable when selectBoxItem.isDisabled for selectBoxItem in allSelectBoxItems"></select>
</td>
<td>
{{product.desc}}
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

Angular Js swap columns in table

I would like to swap 2 columns in a table. Finally, I succeeded the change, but only the data. The attributes of the cell (style, id, class) didn't move. I tried to move attributes with jquery (i know, not an elegant method), but it was only symptomatic treatment. After clicking the data reload button, the attributes restored.
How can I change the columns order with all attributes?
my code: https://codepen.io/qwertz_/pen/YxWMBO
<!DOCTYPE html>
<html>
<head>
<title>angT</title>
<script type="text/javascript" src="http://code.angularjs.org/angular-1.0.0rc10.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
th, td{padding: 3px 20px;border: 1px solid red;}
</style>
</head>
<body>
<div ng-controller="MyCtrl" ng-app="myApp">
<button ng-click="swap(0)">first2second</button>
<button ng-click="reload()">reload</button>
<table id="myTable" >
<tr ng-repeat="row in ths">
<th class="oo1">{{col(row, 0)}}</th>
<th class="oo2">{{col(row, 1)}}</th>
<th class="oo3">{{col(row, 2)}}</th>
<th class="oo4">{{col(row, 3)}}</th>
</tr>
<tr ng-repeat="row in rows">
<td class="o1" style="background-color:yellow;">{{col(row, 0)}}</td>
<td class="o2" style="background-color:pink;">{{col(row, 1)}}</td>
<td class="o3" style="background-color:green;">{{col(row, 2)}}</td>
<td class="o4" style="background-color:blue;">{{col(row, 3)}}</td>
</tr>
</table>
</div>
<script type='text/javascript'>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.mycol = new Array();
$scope.mycol[0] = 'id';
$scope.mycol[1] = 'name';
$scope.mycol[2] = 'db';
$scope.mycol[3] = 'let';
$scope.reload = function()
{
$scope.rows=[{id:parseInt(Math.random()*10000),name:"Liv","db":21,let:"r"},{id:parseInt(Math.random()*10000),name:"Mike",db:30,let:"u"}];
};
$scope.swap = function(i) {
var temp = $scope.mycol[i];
$scope.mycol[i] = $scope.mycol[(i+1)];
$scope.mycol[(i+1)] = temp;
};
$scope.col = function(row, mycol) {
return row[$scope.mycol[mycol]];
};
$scope.reload();
$scope.ths=[{id:"id",name:"name","db":"db",let:"letter"}];
}
</script>
</body>
Thx a lot
Simple way
You can bind colors to header name as:
$scope.styles = {
id: "yellow",
name: "pink"
};
and table will look like:
<tr ng-repeat="row in rows">
<td class="o1" ng-style="{'background-color':styles[mycol[0]]}">{{col(row, 0)}}</td>
<td class="o2" ng-style="{'background-color':styles[mycol[1]]}">{{col(row, 1)}}</td>
<td class="o3" style="background-color:green;">{{col(row, 2)}}</td>
<td class="o4" style="background-color:blue;">{{col(row, 3)}}</td>
</tr>
Once header value changes, colors will change too
Codepen DEMO
More complicated but generic
You can achieve it by replacing all table with directive (headers + data) and by using $compile rebuild all HTML table.

Displaying data using Bootstrap modal/angularjs from asp.net webapi

I'm new to bootstrap. I want to do CRUD operations on the employee data from asp.net WebAPI using Bootstrap-Modal. I'm able to display the data from webapi to angularJS using a table(ng-repeat). In every row, at the end, I've three buttons VIEW, DELETE and EDIT and another outside the table ADD.
I want, whenever a user clicks on the ADD, VIEW, DELETE and EDIT button, a bootstrap modal should pop up and we should be able to perform CRUD operations.
I've tried many instances but no luck on how to get the data on Modal. Please help.
The code is as follows:
WEBAPI:
public class EmployeeService
{
SampleDatabaseEntities sampleDBEntities = new SampleDatabaseEntities();
//ADD USER
public int saveEmployee(EmployeeTable employeeTable)
{
sampleDBEntities.EmployeeTables.Add(employeeTable);
sampleDBEntities.SaveChanges();
return employeeTable.E_ID;
}
public EmployeeTable getEmployeeById(int id)
{
return sampleDBEntities.EmployeeTables.Find(id);
}
public List<EmployeeTable> getEmployees()
{
return sampleDBEntities.EmployeeTables.ToList();
}
public void updateEmployee(int x, EmployeeTable employeeTable)
{
if (employeeTable.E_ID == x)
{
sampleDBEntities.Entry(employeeTable).State = EntityState.Modified;
sampleDBEntities.SaveChanges();
}
}
public void deleteEmployee(int id)
{
var employee = sampleDBEntities.EmployeeTables.Find(id);
if(employee !=null)
{
sampleDBEntities.Entry(employee).State = EntityState.Deleted;
sampleDBEntities.SaveChanges();
}
}
Angular Service:
angular.module('mainApp', []).
factory('employeeService', function ($http) {
var baseAddress = 'http://localhost:53254/api/employee/';
//var baseAddress = 'http://localhost:49595/MobileService/api/UserService/';
var url = "";
return {
getEmployeesList: function () {
url = baseAddress;
return $http.get(url);
},
getUser: function (employee) {
url = baseAddress + "Get/" + employee.E_id;
return $http.get(url);
},
addUser: function (employee) {
url = baseAddress + "post";
return $http.post(url, employee);
},
deleteUser: function (employee) {
url = baseAddress + "Delete/" + employee.E_Id;
return $http.delete(url);
},
updateUser: function (employee) {
url = baseAddress + "put/" + employee.E_Id;
return $http.put(url, employee);
}
};
});
Angular Controller:
angular.module('mainApp')
.controller('getEmployeeCrl', ['$scope', 'employeeService', function ($scope, employeeService) {
employeeService.getEmployeesList().then(function (response) {
$scope.employees = response.data;
}, function (err) {
$scope.errMessage = "Something wrong with server. Please try again.";
})
}]);
HTML:
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<title></title>
<meta charset="utf-8" />
<script src="../Scripts/angular.js"></script>
<script src="../mainApp.js"></script>
<script src="../Utilities/ConstantsFactory.js"></script>
<script src="../Services/EmployeeService.js"></script>
<script src="../Controllers/EmployeeController.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body ng-controller="getEmployeeCrl">
<div>
<h2 style="text-align:center; color:darkblue">PROJECT 51</h2>
</div>
<div class="container">
<div style="background-color:dimgray;color:white;padding:20px;">
<input type="button" value="Go to Employees" class="btn btn-info" />
<input type="button" value="Go to Clients" class="btn btn-info" style="width:145px" />
<button class="glyphicon glyphicon-plus btn btn-primary" value="Add" data-toggle="tooltip" data-placement="top" title="Add Data" style="float:right; width:50px"></button>
</div>
<br />
<table class="table table-bordered table table-condensed" ng-hide="!employees">
<thead style="background-color:palevioletred">
<tr style="text-decoration:solid;color:darkblue;">
<th>Id</th>
<th>Name</th>
<th>Job</th>
<th>Hire Date</th>
<th>Manager</th>
<th>Salary</th>
<th>Commission</th>
<th colspan="2">Edit/Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in employees ">
<td>{{emp.E_ID}}</td>
<td>{{emp.E_NAME}}</td>
<td>{{emp.E_JOB}}</td>
<td>{{emp.HIRE_DATE}}</td>
<td>{{emp.MANAGER_ID}}</td>
<td>{{emp.SALARY}}</td>
<td>{{emp.COMMISSION}}</td>
<td colspan="2" style="width:170px">
<input type="button" ng-model="emp.E_Id" value="View" class="btn btn-primary" style="width:70px" />
<input type="button" value="Edit" class="btn btn-primary" style="width:70px" />
<input type="button" value="Delete" class="btn btn-primary" style="width:70px" />
</td>
</tr>
</tbody>
</table>
<p class="alert alert-danger" ng-show="!employees">{{errMessage}} <span class="glyphicon glyphicon-refresh" ng-show="!employees"></span></p>
</div>
</body>
</html>
How can I make use of Bootstrap Modal for CRUD operations

Angular javascript array is empty?

Angular javascript array is empty?
I have an array of checkboxes databound to an angular scoped list
I need to check a few checkboxes and send bind them to a second angular scoped array:
My HTML:
<tr ng-repeat="item in pagedItems[currentPage]"
ng-controller="DealerComMaintainCtrl">
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}"
ng-value="item.IdArticle"
ng-checked="selected.indexOf(item.IdArticle) > -1"
ng-click="toggleSelect(item.IdArticle)" />
</td>
<td>
<a href="/Dealercoms/ArticleDownload?FileName={{item.FileName}}&IdArticle={{item.IdArticle}}"
class="btn btn-xs btn-total-red btn-label"><i class="ti ti-download"></i></a>
</td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
And JS in the controller:
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
} else {
$scope.selected.splice(index, 1)
}
}
$scope.ArchiveDocs = function() {
var selectedoptionz = $scope.selection;
console.log(selectedoptionz);
};
I tried your code and i fixed the problem, by adding the controller on an element above the ng-repeat. The alert is only to check, what is in the selected-array. This is the code, which works fine on my system:
<html>
<head>
</head>
<body ng-app="app">
<table ng-controller="DealerComMaintainCtrl">
<tbody>
<tr ng-repeat="item in pagedItems" >
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}" ng-value="item.IdArticle" ng-checked="selected.indexOf(item.IdArticle) > -1" ng-click="toggleSelect(item.IdArticle)" />
</td>
<td><i class="ti ti-download"></i></td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
</tbody>
</table>
<!-- jQuery -->
<script src="./jquery-2.1.4/jquery.min.js"></script>
<!-- AngularJS -->
<script src="./angular-1.4.5/angular.min.js"></script>
<script>
var app = angular.module("app", []);
app.controller("DealerComMaintainCtrl", function($scope){
$scope.pagedItems = [
{IdArticle: 1, Title: "test1", Archive: "archiv1"},
{IdArticle: 2, Title: "test2", Archive: "archiv1"},
{IdArticle: 3, Title: "test3", Archive: "archiv1"},
{IdArticle: 4, Title: "test4", Archive: "archiv1"}
];
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
}
else {
$scope.selected.splice(index, 1)
}
alert(JSON.stringify($scope.selected));
}
});
</script>
</body>
</html>
Just try it, i hope it solve your problem...

AngularJS - HTML not updating on variable change

I am trying to learn AngularJS and i am making a test app.
I have a table that gets populated with data returned from a WebService (list of publishers) via $http.get().
When the user clicks a row (publisher) i want to fill a second table with the list of employees of the selected publisher. By using the F12 tools (Network+Console) i see that the data is returned but the second table is not filled/updated.
html
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script src=""></script>
<script src="js/angular.js"></script>
<script src="js/scripts.js"></script>
<script src="js/app.js"></script>
<title>My SPA</title>
</head>
<body>
<header>
<h1 id="page-title">Header</h1>
<nav>
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
</ul>
</nav>
</header>
<div ng-controller='PublishersController' class="table-wrapper">
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in publishers[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='pub in publishers' ng-click='getPublishersEmployees(pub.pub_id)'>
<td ng-repeat='(key,val) in pub'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
<div ng-controller='PublishersController' class="table-wrapper">
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in employees[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='employee in employees'>
<td ng-repeat='(key,val) in employee'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
JS
var urlBase = "http://localhost:2041";
var app = angular.module('myApp', []);
app.factory('myFactory', ['$http', function ($http) {
var webAPI = '/api/query';
var webService = urlBase + webAPI;
var myFactory = {};
myFactory.getCategories = function () {
return $http.get(webService + '/getCategories');
};
myFactory.getCategorySalesByMonth = function (id) {
return $http.get(webService + '/getCategorySalesByMonth/' + id);
};
myFactory.getPublishers = function () {
return $http.get(webService + '/getPublishers');
};
myFactory.getPublishersEmployees = function (id) {
return $http.get(webService + '/getPublishersEmployees/' + id);
};
return myFactory;
}]);
app.controller('PublishersController', ['$scope', 'myFactory',
function ($scope, myFactory) {
$scope.status;
$scope.publishers;
$scope.employees;
getPublishers();
function getPublishers() {
myFactory.getPublishers()
.success(function (publishers) {
$scope.publishers = publishers;
})
.error(function (error) {
$scope.status = 'Unable to load publishers data: ' + error.message;
});
}
$scope.getPublishersEmployees = function (id) {
myFactory.getPublishersEmployees(id)
.success(function (employees) {
$scope.employees = employees;
console.log($scope.employees);
})
.error(function (error) {
$scope.status = 'Error retrieving employees! ' + error.message;
});
};
}]);
What am i doing wrong?
The problem is you use separate controllers for PublishersController and EmployeesController. Angular will create separate scopes for your controllers. Therefore, when you assign $scope.employees = employees in your PublishersController, it does not reflect on the scope created by EmployeesController
Try:
<div ng-controller='PublishersController' class="table-wrapper">
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in publishers[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='pub in publishers' ng-click='getPublishersEmployees(pub.pub_id)'>
<td ng-repeat='(key,val) in pub'>{{val}}</td>
</tr>
</tbody>
</table>
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in employees[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='employee in employees'>
<td ng-repeat='(key,val) in employee'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
That solution above is just to point out your problem. I don't know your application design, you may not follow this solution but restructure your code to best fit your application design (like storing the employees in a shared service,...).
Here I propose another solution but I'm not sure if it fits with your application. You just use your original HTML code with PublishersController and EmployeesController. In your PublishersController, your could broadcast an event from rootScope:
.success(function (employees) {
$rootScope.$broadcast("employeeLoaded",employees);
})
Don't forget to inject $rootScope to your PublishersController:
app.controller('PublishersController', ['$scope', 'myFactory','$rootScope',
function ($scope, myFactory,$rootScope)
In your EmployeesController, you could subscribe to this event:
$scope.$on("employeeLoaded",function (event,employees){
$scope.employees = employees;
});
For more information about event in angular, check out Working with $scope.$emit and $scope.$on

Resources