Inline edit in angular - angularjs

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?

Related

Get angularjs post value in controller

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.

How to prevent destroy data from DataTable with Angular

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....

how do I add data to angular smart table

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>

Angular doesn't refresh the table after adding new item

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>

Edit Ng-Repeat inline with REST API

I have been at this for awhile now but in short I am making a UI that allows our users to modify a MySQL DB using an Angular frontend and Slim PHP to serve up the REST.
I continue to get an error stating that 'firstName' is not defined as a column and I cant seem to figure out why. I believe it has something to do with the way the ng-repeat works and how I can assign / call objects inside of it but I am stuck!
Here is the HTML, App.js and index.php - The code is a little hacked up but I want to edit the rows in-line.
Any knowledge is much appreciated as I have just started using Angular and REST this year!
List.html
<div class="row">
<div class="col-lg-12">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address 1</th>
<th>Address 2</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th class="text-center">Edit</th>
</tr>
</thead>
<tbody ng-repeat="referral in referrals | filter:query | limitTo:limitBy | orderBy:lastName">
<tr >
<td>{{referral.ID}}</td>
<td>
<!-- <span id="firstName" data-ng-hide="editMode">{{referral.firstName}}</span>-->
<span data-ng-hide="editMode">{{referral.firstName}}</span>
<input type="text" data-ng-show="editMode" ng-model="referral.firstName"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.lastName}}</span>
<input type="text" data-ng-show="editMode" ng-model="referral.lastName"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.address1}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.address1"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.address2}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.address2"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.city}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.city"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.state}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.state"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.zipCode}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.zipCode"/>
</td>
<td class="text-center">
<button type="submit" data-ng-hide="editMode" data-ng-click="editMode = true; editAppKey(entry)" class="btn btn-default">Edit</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; saveField(referral)" class="btn btn-default">Save</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; cancel()" class="btn btn-default">Cancel</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
App.js
app.controller('viewController', function($resource, $scope, $location, $route, $routeParams) {
$scope.title = 'Endo Admin';
$scope.query = {};
$scope.queryBy = 'lastName';
$scope.limitBy = '50';
var Referrals = $resource('http://pdgrosit02v/endoAdmin/app/api/referrals');
$scope.referrals = Referrals.query();
$scope.newField = {};
$scope.editing = false;
$scope.editAppKey = function(field) {
$scope.editing = $scope.referrals.indexOf(field);
$scope.newField = angular.copy(field);
}
$scope.saveField = function(index) {
// if ($scope.editing !== false) {
// var Referral = $resource(('http://pdgrosit02v/endoAdmin/app/api/referral/'+ index.ID));
//
// $scope.referral = Referral.get();
//
$scope.referral = $scope.newField;
// $scope.editing = false;
var ReferralPut = $resource(('http://pdgrosit02v/endoAdmin/app/api/referral/'+ index.ID), {}, { update: { method: 'PUT'}} );
ReferralPut.update($scope.referral, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
};
});
index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app = new Slim();
$app->get('/referrals', 'getReferrals');
$app->get('/referral/:id', 'getReferral');
$app->put('/referral/:id', 'updateReferral');
$app->run();
function updateReferral($id) {
$referral = Slim::getInstance()->request()->getBody();
$data = json_decode($referral, true);
$sql = "UPDATE endo_referral SET firstName=:first_Name, lastName=:last_Name WHERE ID=$id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue(":first_Name", $data['firstName']);
$stmt->bindValue(":last_Name", $data['lastName']);
$stmt->execute();
$db = null;
echo json_encode($data);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
In the $scope.saveField function, you should use the passed-in referral. Instead of
...
ReferralPut.update($scope.referral, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
...
Looking at your code, it looks like this needs to be:
ReferralPut.update(index, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
The $scope.saveField function is passed the current referral in the index field. $scope.referral is undefined in the saveField function.
There may be other issues, but this was the one that stood out the most.

Resources