Angular: insert an ID to a api path - angularjs

I am stuck with this problem:
I'm trying to delete a row from a table by passing the ID of that row (i.e. record) into the path of my API. Unfortunately it isn't recognized. However, when I replace $scope.ID with a hardcoded ID-number, all is working as expected.
This is my code:
Controller:
$scope.go = function(record) {
$scope.ID = record.ID;
}
$scope.deleteRow = function() {
$http.delete("api.php/bml/"+$scope.ID)
.success(function(data, status, headers, config){
console.log('successfully deleted ID: ' + $scope.ID);
})
};
Of course in my HTML I have a TR tag with ng-click="go(record) in it.
Strange enough the right ID number is showing up in the console.log message!

Use like this
$scope.deleteRow = function(ID) {
$http.delete("api.php/bml/"+ID)
.success(function(data, status, headers, config){
console.log('successfully deleted ID: ' + ID);
})
};
EDIT:
<button ng-click="deleteRow(id)">Delete</button>

Related

Retain Session value in jsp page using Angularjs

I'm using Angularjs and Spring .....
I had set the Session value for certain text fields using angularjs sessionstorage . When is reload the page or move backwards from other jsp page those values must retain in respective fields
$window.sessionStorage.setItem('namednewicno',$scope.user.namednewicno);
This is the session value for namednewicno
I need to display that value using data-ng-model
This is my controller
app.controller('FormSubmitController',[ '$scope', '$http','$window', function($scope, $http,$window) {
$scope.user = [];
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.submit = function() {
$window.localStorage.setItem('namednewicno',$scope.user.namednewicno);
$window.sessionStorage.setItem('namednewicno',$scope.user.namednewicno);
var formData = {
"namednewicno" : $scope.user.namednewicno,
"namedoldicno" : $scope.user.namedoldicno,
"namedage" : $scope.user.namedage,
"nameddriverexperience" : $scope.user.nameddriverexperience,
"namedgender" : $scope.user.namedgender,
"nameddrivername" : $scope.user.nameddrivername,
"nameddriverrelationship" : $scope.user.nameddriverrelationship
};
alert("controller");
var response = $http.post('PostFormData', formData);
response.success(function(data, status, headers, config) {
$scope.user.push(data);
alert("success");
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
$scope.user.namednewicno=$window.sessionStorage.getItem( 'namednewicno' );
console.log($window.sessionStorage.getItem( 'namednewicno' ));
//Empty list data after process
// $scope.user = [];
};
}]);
app.controller('NamedPopup',[ '$scope', '$http','$window', function($scope, $http,$window) {
$scope.user = [];
$scope.user.namednewicno=$window.sessionStorage.getItem( 'namednewicno' );
$scope.submit = function() {
$window.sessionStorage.setItem('namednewicno',$scope.user.namednewicno);
var formData = {
"namednewicno" : $scope.user.namednewicno
};
var response = $http.post('saveNamedDrivers', formData);
response.success(function(data, status, headers, config) {
$scope.user.push(data);
//alert("success");
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.user = [];
};
}]);
The Html code must be like this to retain the session on html
<input ng-value="{{user.namednewicno}}"
ng-model="user.namednewicno"
required
class="form-control" type="number" />

update database from angular-ui-grid

I am trying to change a row in my database when the user clicks the delete button in my angular ui-grid. When the button is clicked, the row should be removed from the grid, and the table in the database should be updated with a value so that the row will no longer appear in the grid, but it will still be in the database (soft-delete). My table is called applicants and has rows id, firstname, lastname, email, position, resume, and deleted. Deleted is a boolean column defaulted to false, if true, the row should not appear in my ui-grid. I have this portion completed, however I cannot get my code to update the deleted column in the database when the button is pressed on the grid. This is the controller for the grid (gets the applicants from the database):
angular.module('myApp')
.controller('gridController',['$scope','$http','$log',function ($scope, $http,$log){
$scope.deleteRow = function(row) {
var index = $scope.gridOptions.data.indexOf(row.entity);
$scope.gridOptions.data.splice(index, 1);
$http({
method:'POST',
url:'/directives/updateApplicant'
})
}
$scope.gridOptions = {
enableFiltering:true,
columnDefs: [
{name: 'id', field:'id'},
{name:'firstName',field:'firstName'},
{name:'lastName',field:'lastName'},
{name:'email',field:'email'},
{name:'position',field:'position'},
{name:'resume', field:'resumeFileName', cellTemplate:'<div class="ui-grid-cell-contents">{{ COL_FIELD }}</div>'},
{name:'delete',cellTemplate: '<button class="btn primary" ng-click="grid.appScope.deleteRow(row)">Delete</button>', enableFiltering:false}
]
}
$scope.data = []
$http({
method:'GET',
url:'/directives/applicants'
}).then(function(success){
$scope.gridOptions.data = success.data;
},function(reason){
$scope.error = reason.data;
$log.info(reason);
})
}])
when it hits the post route this code runs:
module.exports.updateApplicant = function(req,res){
applicant.forge({id: '31'})
.fetch({require:true})
.then(function(applicant){
applicant.save({
deleted:'true'
})
.then(function(){
res.json({error:false,data:{message:'applicant details updated'}})
})
.catch(function(err){
res.status(500).json({error:true, data:{message: err.message}})
});
})
.catch(function(err){
res.status(500).json({error:true,data:{message:err.message}})
})
}
this works just fine the only problem is that i have the ID hardcoded. Is there a way i can pass the ID from the selected row in the grid to this variable?
Send http request when you click button
$scope.deleteRow = function(row) {
var index = $scope.gridOptions.data.indexOf(row.entity);
$scope.gridOptions.data.splice(index, 1);
$http({
method:'POST',
url:'/directives/updateApplicant',
data: $scope.gridOptions.data[index],
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log("success");
}).error(function (data, status, headers, config) {
console.log(status);
})
}
you need install body-parser and use it as middleware (app.use(bodyParser.urlencoded({ extended: false })) to get the POST body.
module.exports.updateApplicant = function(req,res){
var bid = req.body.id;
applicant.forge({id: bid})
.fetch({require:true})
.then(function(applicant){
applicant.save({
deleted:'true'
})
.then(function(){
res.json({error:false,data:{message:'applicant details updated'}})
})
.catch(function(err){
res.status(500).json({error:true, data:{message: err.message}})
});
})
.catch(function(err){
res.status(500).json({error:true,data:{message:err.message}})
})
}

How to perform update(PUT) call in angularjs?

I am new to angularjs.
I have following UI template DashBoard.html
on click of CREATE NEW EVENTS i am posting data to server.
In the screen shot above => is EDIT functionality.
On click of that pencil symbol I am displaying below UI template.
Manage-CMS.html
Now I want to fill those empty text boxes with the pre-filled value.
and also onclick of SAVE button I want to update that data to server.
How could I achieve that ?
Please help.
CODE I am trying:
codeApp.controller('DashboardController', function($scope, $rootScope, $location, $http) {
$scope.username = "Admin";
$scope.apps = [];
$scope.initController = function(){
var appDetails = new Array();
var appObject = new Object();
$scope.id = sessionStorage.id;
$http.get('http://192.168.1.30:8090/apps/').
success(function(data, status, headers, config) {
console.log(data);
for(var key in data._embedded.apps){
appObject = data._embedded.apps[key];
appDetails.push(appObject);
$rootScope.appId = data._embedded.apps[key].appId;
}
$scope.appDetails = appDetails;
}).
error(function(data, status, headers, config) {
alert("Failed to load app details");
});
};
$scope.go = function (path) {
$location.path(path);
var display = false;
if(!display){
}
};
$scope.addApp = function(){
$scope.apps.push({'name':$scope.name, 'domain': $scope.domain, 'appId' : $scope.appId, 'secret' : $scope.secret});
// Writing it to the server
//
var dataObj = {
name : $scope.name,
domain : $scope.domain,
appId : $scope.appId,
secret : $scope.secret
};
var res = $http.post('http://192.168.1.30:8090/apps/', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
// Making the fields empty
//
$scope.name='';
$scope.domain='';
$scope.appId = '';
$scope.secret = '';
};
});
NOTE: same SAVE button is used for both server side functionality i.e. POST and PUT
You can pass the data of that row on click of the edit button, the easiest way to do this is to use a modal ( I prefer using bootstrap based angular-bootstrap by angular-ui https://github.com/angular-ui/bootstrap ).
Pass the data of your ng-repeat row to the modal and then update the data in the form. On save you can call $http.put/post to update the data to the server.

Cascading Dropdown Binding On Edit Click Angular

I want to bind dropdowns in edit mode but with value selected according to each record
My Edit View
<select ng-model="user.StateId" ng-init="user.StateId=#Model.StateId" data-ng-options="s.Id as s.State for s in States " data-ngchange="GetCities()"></select>
<select ng-model="user.CityId" data-ng-options="c.Id as c.City for c in Cities " ></select>
My Angular Js
function GetStates() {
$http({
method: 'Get',
url: '/Home/GetStates'
}).success(function (data, status, headers, config) {
$scope.States = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
$scope.GetCities = function (obj) {
var stateId = $scope.user.StateId;
alert(stateId);
if (stateId) {
$http({
method: 'POST',
url: '/Home/GetCities/',
data: JSON.stringify({ stateId: stateId })
}).success(function (data, status, headers, config) {
$scope.Cities = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.states = null;
}
}
$scope.edit = function (user) {
var ref = user;
$http
({
method: 'GET',
dataType: 'html',
url: location.href = '../Home/Edit?Id=' + ref.Id,
})
}
Now when user click on edit i want to open user details in edit mode and i m doing so using $scope.edit user is my object in which i m getting data to edit now i want dropdown of edit view to show state and city selected as per the state and city i got as a response in function(user)

How can I use ng-click to dynamically reload ng-repeat data?

I have a page that contains an ng-repeat directive. The ng-repeat works when the page first loads, but I want to be able to use ng-click to refresh the contents of the ng-repeat. I have tried the following code but it doesn't work. Any suggestions?
<div ng-click="loadItems('1')">Load 1st set of items</div>
<div ng-click="loadItems('2')">Load 2nd set of items</div>
...
<table>
<tr ng-repeat="item in items">>
// stuff
</tr>
</table>
ItemsCtrl:
$scope.loadItems = function (setID) {
$http({
url: 'get-items/'+setID,
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.items = data;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
I was hoping that my call to loadItems() would cause the ng-repeat directive to reload with the new data obtained from my server.
Add a broadcast in your callback and subscribe to it in your controller.
This should really be in a service btw
itemsService.loadItems = function (setID) {
$http({
url: 'get-items/'+setID,
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.items = data;
$rootScope.$broadcast('updateItems', data);
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
In your controller:
$scope.$on("updateItems",function(d){
$scope.items = d;
});
So whenever you ng-click="update(id)"
$scope.update = function(id){
itemsService.loadItems(id);
}
Your items will automatically update because it is subscribed.

Resources