I have a simple angular smart-table. It loads the data correctly. If i remove some data the table updates correctly, however if I add data, the table doesnt update. Does anybody know what I am doing wrong. Help would be much appreciated!
HTML:
<div class="container">
<!-- Angular Grid -->
<div ng-controller="MainCtrl">
<table st-table="displayedCollection" class="table table-striped" st-safe-src="rowCollection">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>birth date</th>
<th>balance</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in displayedCollection">
<td>{{row.naam}}</td>
<td>{{row.naam2}}</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>
<button type="button" id="addData" class="btn btn-success" ng-click="addRandomItem(row)">Add Data</button>
<div ng-show='busy'>Loading data...</div>
</div>
</div>
And the Controller:
(
(function() {
'use strict';
angular
.module('app')
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$state', 'Auth', '$modal', 'scrapeAPI', '$http', '$alert', 'recommendationsAPI', 'Upload'];
function MainCtrl($scope, $state, Auth, $modal, scrapeAPI, $http, $alert, recommendationsAPI, Upload) {
$scope.displayedCollection = [];
$scope.user = Auth.getCurrentUser();
$scope.rowCollection = [];
$scope.recommendation = {};
$scope.recommendations = [];
$scope.recommendationPostForm = true;
$scope.busy = true;
$scope.allData = [];
var i = 0;
var page = 0;
var step = 3;
var data1 = [];
//gets current data
recommendationsAPI.getAllRecommendations()
.then(function(data) {
console.log('looks found ');
console.log(data);
$scope.recommendations = data.data;
for (i = 0; i < $scope.recommendations.length; i++) {
$scope.rowCollection.push($scope.recommendations[i]);
}
$scope.busy = false;
})
.catch(function(err) {
console.log('failed to get looks ' + err);
});
$scope.addRandomItem = function addRandomItem() {
$scope.recommendation = {
naam: 'tje',
naam2: 'tje'
};
$scope.recommendations.push($scope.recommendation);
for (var j = 1; j < $scope.recommendations.length; j++) {
alert ($scope.recommendations[j].guideline);
}
$scope.rowCollection.push($scope.recommendation);
};
// Verwijder recommendation volledig
$scope.removeItem = function removeItem(row) {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
recommendationsAPI.deleteRecommendation($scope.rowCollection[index]._id)
.then(function(data) {
console.log('delete at backend: success');
$scope.rowCollection.splice(index, 1);
});
}
}
}
})();
Your button "addRandomItem" is out of the div which holds your controller, so it can not access its scope
<div class="container">
<!-- Angular Grid -->
<div ng-controller="MainCtrl">
<table st-table="displayedCollection" class="table table-striped" st-safe-src="rowCollection">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>birth date</th>
<th>balance</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in displayedCollection">
<td>{{row.naam}}</td>
<td>{{row.naam2}}</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>
<button type="button" id="addData" class="btn btn-success" ng-click="addRandomItem(row)">Add Data</button>
</div>
<div ng-show='busy'>Loading data...</div>
</div>
Related
I want to get post value which i have send in $http.post() in controller when i click on edit button.
view page
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sl No.</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in datas">
<td>{{$index + 1}}</td>
<td>{{data.name}}</td>
<td>
<a class="btn btn-info btn-sm btn-fill" ng-click="editsource(data.id)" data-toggle="modal" data-target="#myModal"><i class="fa fa-pencil-square-o"></i> Edit</a>
<a class="btn btn-danger btn-sm btn-edit btn-fill delete"><i class="fa fa-trash"></i> Delete</a>
</td>
</tr>
</tbody>
My script
<script type="text/javascript">
var app = angular.module('myapp', []);
app.controller('tabletest', function ($scope, $http) {
$http.get("<?php echo base_url() ?>admin/source_list_for_test")
.then(function (response) {
$scope.datas = response.data;
});
$scope.editsource = function (id) {//alert('hello');
$http.post("<?php echo base_url() ?>admin/edit_source_for_test?id="+id).success(function (data) {
alert(data);
$scope.id = data['id'];
$scope.name = data['name'];
});
};
});
controller
public function edit_source_for_test(){
$id= $_GET['id'];
$data['source_data'] = $this->admin_model->get_edit_source_for_test($id);
echo json_encode($data['source_data']);
}
Above is my code but id not get in controller,How i get selected record id in controller.
I did one simple inline edit in angular.Its working fine,But when I try to integrate with server side code am getting struggle.I dont know how to send edited field value while updating.
html:
<table class="table table-hover table-bordered" id="mydata" ng-controller="myCtrl">
<thead class="colorBlue">
<tr>
<th>S.No</th>
<th>Role Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="">
<tr ng-repeat="x in roleList | filter:searchText">
<td>{{x.Id}}</td>
<td>
<span ng-hide="editMode">{{x.name}}</span>
<input type="text" ng-show="editMode" ng-model="x.name" />
</td>
<td>
<i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
<i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="editMode = false"></i>
<i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
</td>
</tr>
</tbody>
</table>
script:
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.values = {
};
$http.post("/Admin/getUserList")
.then(function (response) {
$scope.roleList = response.data;
});
$scope.edit=function(val){
$scope.editing = $scope.items.indexOf(val);
}
$scope.update = function (val) {
$http.post("/Admin/UserUpdate")
.then(function (response) {
alert("updated successfully");
})
}
//$scope.cancel = function (val) {
//}
})
</script>
Am getting table data from this method /Admin/getUserList
while updating the rows I need to pass edited data to this method /Admin/UserUpdate
Please any help?
How do you get the ng-click event to actually fire? I've tried everything to get this to work. I know the alert is working initially, but after the list is displayed, quite magically all the buttons fail to function.
Here is the display of the page (pre/post alert). I've verified that each button for details is getting a unique id. As you can see, I've also tried $parent (since some of the buttons are within a ng-repeat) as well as $rootscope to try to get things to execute (i.e. the detail buttons). It's almost as if, after the initially display, the page has lost the reference to the angularjs file since nothing functions:
When page is first displayed
After getting the data
Here's the AngularJS file:
var app = angular.module("EmployeeApplication", [])
.controller("EmployeeController",
function ($scope, $http,$window) {
AngularInit();
function AngularInit() {
//This will be called once per form load, via the ng-load function on the div
$scope.name = '';
$scope.gender = '';
$scope.salary = '';
$scope.id = '';
$scope.DisplayAction = 'Unknown';
$scope.gotdata = false;
DisplayList();
ShowAlert('test')
}
function GetAllEmployees($http) {
//$scope.Message = 'NULL';
//$scope.employees = {};
$http.get('http://localhost:65315/api/employee').then(function (response) {
$scope.employees = response.data;
$scope.Message = 'OK';
$scope.gotdata = true;
},
function (err) {
$scope.Message = 'Call failed' + err.status + ' ' + err.statusText;
$scope.employees = {};
$scope.gotdata = false;
}
);
//window.setTimeout(function () {
// $scope.gotdata = true;
//}, 1000);
};
function DisplayList() {
//call the web service to get the list of people
//set the display action so that the list will be displayed
GetAllEmployees($http)
$scope.DisplayAction = 'List';
};
function CreateNewEmployee() {
$scope.name = '';
$scope.gender = '';
$scope.salary = '';
$scope.id = '';
$scope.DisplayAction = 'Create';
$scope.$apply();
};
function ShowDetails(id) {
//call the web service to get the details of the person
ShowAlert('test')
$scope.gotdata = false;
$http.get('http://localhost:65315/api/employee/' + id).then(function (response) {
$scope.employees = response.data;
$scope.DisplayAction = 'Details';
$scope.Message = 'OK';
},
function (err) {
$scope.Message = 'Call failed' + err.status + ' ' + err.statusText;
$scope.employees = {};
}
);
//Set the $scope.CurrentEmployee
$scope.$apply();
};
function ShowAlert(msg)
{
$window.alert(msg);
}
function CreateEmployee() {
//perform the actual creation based on $scope.CurrentEmployee
//if successful
DisplayList();
};
function DeleteEmployee(id) {
$scope.DisplayAction = 'Delete';
$scope.$apply();
};
function DoDeleteEmployee(id) {
//Perform actual deletion
//if successful
DisplayList();
};
function EditEmployee(id) {
//get the employee based on ID
$scope.DisplayAction = 'Edit';
$scope.$apply();
};
function EditUpdate() {
//perform the actual update based on $scope.id
//if successful
DisplayList();
};
}
);
//angular.module('EmployeeApplication', [])
// .controller('EmployeeController', ['$scope', '$window', function ($scope, $window) {
// $scope.greeting = 'Hello, World!';
// $scope.doGreeting = function (greeting) {
// $window.alert(greeting);
// };
// }]);
var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http)
{
$scope.MadeItHereMessage = 'We made it to the controller (first controller)';
$scope.employees = {};
$http.get('http://localhost:65315/api/employee').then(function (response) {
$scope.employees = response.data;
$scope.Message = "OK";
},
function (err)
{
$scope.Message = "Call failed" + err.status + " " + err.statusText;
}
);
});
//var app = angular.module("MyModule", []).controller("MyController", function initController($scope)
//{
// $scope.MadeItHereMessage = 'This is a loadtest';
//});
//var app = angular.module("EmployeeApplication", ['$rootscope','$scope','$http'])
//.controller("EmployeeController",
// function AppCtrl($rootscope,$scope, $http)
// {
// $scope.DisplayAction = "List";
// }
//);
//var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http) {
// $http.get('EmployeeWebService.asmx/GetAllEmployees').then(function (response) {
// $scope.employees = response.data;
// }
// );
//});
Here is the HTML file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/EmployeeAngular.js"></script>
<meta charset="utf-8" />
</head>
<body ng-app="EmployeeApplication">
<div ng-controller="EmployeeController" ng-init="AngularInit()">
{{Message}}
<br/>
{{DisplayAction}}
<button id="btnCreateNew1" ng-click="$parent.ShowAlert('Parent scope button pressed')">Show message from parent scope</button>
<br />
<!--The following is for listing the entire list of employees-->
<div id="listSection" ng-show="DisplayAction=='List'">
<!--The employees data is: {{employees}}-->
<!--<div id="listSection">-->
<table>
<thead>List of defined Employees</thead>
<tr>
<!--<td><button id="btnCreateNew" ng-click="CreateNewEmployee()">Create Employee</button></td>-->
<td><button id="btnCreateNew" ng-click="$rootscope.ShowAlert('Create button pressed')">Create Employee</button></td>
</tr>
<tr>
<td ng-show="gotdata">
<table id="EmployeeList">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees" ng-if="employees && employees!={undefined}">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.salary}}</td>
<td><button id="btnDetailsA{{employee.id}}" ng-click="$parent.ShowDetails({{employee.id}})">Details</button></td>
<td><button id="btnDetailsB{{employee.id}}" ng-click="$parent.ShowDetails({{employee.id}})">Details B</button></td>
<td><button id="btnDetailsC{{employee.id}}" ng-click="ShowDetails({{employee.id}})">Details C</button></td>
<td><button id="btnDetailsD{{employee.id}}" ng-click="$scope.ShowDetails({{employee.id}})">Details D</button></td>
<td><button id="btnDetailsE{{employee.id}}" ng-click="$rootscope.ShowDetails({{employee.id}})">Details E</button></td>
<td><button id="btnDelete{{employee.id}}" ng-click="$parent.DeleteEmployee({{employee.id}})">Delete</button></td>
<td><button id="btnEdit{{employee.id}}" ng-click="$parent.EditEmployee({{employee.id}})">Edit</button></td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</div>
<!--The following is for listing the details of a single employee-->
<div id="DetailsSection" ng-show="DisplayAction=='Details'">
<table>
<tr>
<td>ID:</td>
<td> <input id="DetailsID" value={{employee.id}} /></td>
</tr>
<tr>
<td>Name:</td>
<td><input id="DetailsName" value={{employee.name}} /> </td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="DetailsGender" value={{employee.gender}} /> </td>
</tr>
<tr>
<td>Salary:</td>
<td><input id="DetailsSalary" value={{employee.salary}} /> </td>
</tr>
<tr>
<td>
<button id="NavTolist" ng-click="DisplayList()">Back to List</button>
</td>
<td>
<button id="NavToDelete" ng-click="DeleteEmployee({{id}})">Delete</button>
</td>
<td>
<button id="NavToEdit" ng-click="EditEmployee({{id}})">Edit</button>
</td>
</tr>
</table>
</div>
<!--The following is for editing a employee-->
<!--<div id="EditSection" ng-show="DisplayAction=='Edit'">
<table>
<tr>
<td>ID:</td>
<td>
<input id="ID" value={{id}} />
</td>
</tr>
<tr>
<td>Name:</td>
<td><input id="" value={{name}} ng-bind="name" /> </td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="" value={{gender}} ng-bind="gender" /> </td>
</tr>
<tr>
<td>Salary:</td>
<td><input id="" value={{salary}} ng-bind="salary" /> </td>
</tr>
<tr>
<td>
<button id="EditUpdate" type="button" value="Update" ng-click="EditUpdate()"></button>
</td>
<td>
<button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button>
</td>
<td>
<button id="NavToDeleteEdit" type="button" value="Delete" ng-click="DeleteEmployee({{id}})"></button>
</td>
</tr>
</table>
</div>-->
<!--The following is for verification of deletion-->
<div id="DeletionSection" ng-show="DisplayAction=='Delete'">
<table>
<tr>
<td>Do you really want to delete {{name}}</td>
<td></td>
<td>
<button id="btnCancelDelete" type="button" value="No" ng-click="DisplayList()"></button>
</td>
<td>
<button id="btnDeleteEmployee" type="button" value="Yes" ng-click="DoDeleteEmployee({{id}})"></button>
</td>
</tr>
</table>
</div>
<!--The following is for creation of a employee-->
<!--<div id="CreationSection" ng-show="DisplayAction=='Create'">
<table>
<tr>
<td>Name:</td>
<td><input id="" value="" ng-bind="name" /> </td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="" value="" ng-bind="gender" /> </td>
</tr>
<tr>
<td>Salary:</td>
<td><input id="" value="" ng-bind="salary" /> </td>
</tr>
<tr>
<td>
<button id="btnCreateEmployee" type="button" value="Delete" ng-click="CreateEmployee()"></button>
</td>
<td>
<button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button>
</td>
</tr>
</table>
</div>-->
</div>
</body>
</html>
unlike vanilla event handlers, ng-click will look for a event handler in the controller scope, so when you have:
<button id="NavTolist" ng-click="DisplayList()">Back to List</button>
your controller must have:
$scope.DisplayList = function() {
//call the web service to get the list of people
//set the display action so that the list will be displayed
GetAllEmployees($http)
$scope.DisplayAction = 'List';
};
you might be interested in take a look in a few sample projects over the web in order to better organize your code.
on a side note, whenever possible sample your web-capable code on plunker / jsfiddle / codepen, since it provides a huge help for anyone willing to help.
I'm try to implement DataTables with Angular, I'm googled and some many solutions is creating directives, its ok but is very old only "normal" way draw a DataTable, the problem is sorting or typing into search box my data is lost!! E.g:
And my code:
View
var myApp = angular.module('myApp', ['ngRoute','ui.utils']);
myApp.controller("CompanyController", function ($scope, $window, CompanyService) {
$scope.Companies = [];
$scope.Company = {};
$scope.dataTableOpt = {
//custom datatable options
"aLengthMenu": [[10, 50, 100, -1], [10, 50, 100, 'All']],
};
$scope.$watch("data", function (value) {
console.log("Data changed, refresh table:");
var val = value || null;
if (val) {
}
});
$scope.InitializeIndexView = function () {
var getAllProcess = CompanyService.GetAllCompanies();
getAllProcess.then(function (response) {
//console.log(response.data)
$scope.Companies = response.data;
},
function (response) {
console.log(response);
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<table id="company-table" class="table table-striped table-bordered" ui-jq="DataTable" ui-options="dataTableOpt">
<thead>
<tr>
<th>Id</th>
<th>Register time</th>
<th>Short Name</th>
<th>Long Name</th>
<th>Status</th>
<th>Owner Client</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in Companies">
<td>{{item._id}}</td>
<td>{{item.RegisterTime}}</td>
<td>{{item.LongName}}</td>
<td>{{item.ShortName}}</td>
<td>{{item.CompanyStatus}}</td>
<td>{{item.OwnerClient}}</td>
<td>Edit | Delete</td>
</tr>
</tbody>
</table>
Edit 1:
I follow these snippet and works fine because data is static: http://codepen.io/kalaiselvan/pen/RRBzda
Angular Js
var app = angular.module('myApp', ['datatables']);
app.controller("myCtrl", function ($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
$scope.isDisabledupdate = true;
$scope.GetAllData = function () {
$http({
method: "get",
url: "http://localhost:8200/Employee/Get_AllEmployee"
}).then(function (response) {
$scope.employees = response.data;
}, function () {
alert("Error Occur");
})
};
$scope.vm = {};
$scope.vm.dtOptions = DTOptionsBuilder.newOptions()
.withOption('order', [0, 'asc']);
View Page
<div class="panel-body" ng-init="GetAllData()">
<div class="table-responsive">
<table class="table table-striped table-bordered" datatable="ng" dt-options="vm.dtOptions">
<thead>
<tr>
<th>S.no</th>
<th>
ID
</th>
<th>
City Name
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="Emp in employees">
<td>{{$index+1}}</td>
<td>
{{Emp.CId}}
</td>
<td>
{{Emp.CityName}}
</td>
<td>
<button type="button" class="btn btn-default btn" ng-click="getCustomer(Emp)"><i class="glyphicon glyphicon-pencil"></i></button>
<button type="button" class="btn btn-default btn" ng-click="deleteemp(Emp)"><i class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-datatables.min.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src='https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js'></script>
I hope this code will help you....
When i get GetAll(); angular function to refresh the table it called Because i get the alert message but it doesn't refresh the table.
I am new in AngularJS and i don't know how to solve that problem
Please help me
Here is my code:
[HttpGet]
public JsonResult GetAllContinents()
{
MyDatabaseEntities db = new MyDatabaseEntities();
var Result = (from con in db.Continents select new { ContinentId = con.ContinentId, ContinentName = con.ContinentName.Trim() }).ToList();
return Json(Result, JsonRequestBehavior.AllowGet);
}
HTML:
<div data-ng-controller="myCntrl">
<div class="col-md-12">
<table class="table table-bordered table-hover" style="width:800px">
<thead>
<tr>
<th><b></b>ID<b></b></th>
<th>continent Name</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="con in ContinentsList">
<td>{{con.ContinentId}}</td>
<td>{{con.ContinentName}}</td>
<td>
<button class="btn btn-md glyphicon glyphicon-trash"
title="Click here to delete record" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div data-ng-controller="myCntrl">
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
AngularJs:
app.controller("myCntrl", function ($scope, $http, angularService) {
$scope.GetAll = function () {
$scope.ContinentsList = [];
$http.get('/Home/GetAllContinents')
.success(function (data) {
$scope.ContinentsList = data;
alert('Done!')
})
.error(function (msg) {
alert(msg);
})
};
$scope.GetAll();
$scope.AddContinent = function () {
$http.post('/Home/AddContinent', { Con: $scope.Continent })
.success(function (data) {
$scope.clear();
$scope.GetAll();
})
.error(function (msg) {
alert(msg)
})
};`enter code here`
Thank you in advance
You have to define the Continental ist ouside the function scope.
$scope.ContinentsList = [];
function getAll () {
$http.get('/Home/GetAllContinents')
.success(function (data) {
$scope.ContinentsList = data;
alert('Done!')
})
.error(function (msg) {
alert(msg);
})
};
Remove ng-controller from :
<div data-ng-controller="myCntrl">
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
Now you have two scope and two lists of content and it's problem. In one scope you have a list that you show on view and in second scope you add elements and try refresh lists.
This is working code:
<div data-ng-controller="myCntrl">
<div class="col-md-12">
<table class="table table-bordered table-hover" style="width:800px">
<thead>
<tr>
<th><b></b>ID<b></b></th>
<th>continent Name</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="con in ContinentsList">
<td>{{con.ContinentId}}</td>
<td>{{con.ContinentName}}</td>
<td>
<button class="btn btn-md glyphicon glyphicon-trash"
title="Click here to delete record" />
</td>
</tr>
</tbody>
</table>
</div>
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>