Hi I am trying to update my data in angularJS(frontend) and laravel(backend).
But even I got an data from id, but I always make a new data.
I thought it cause my laravel code's fault, but not sure.
AngularJS service
app.factory('Assets', function($resource) {
return $resource('/api/assets/:assetId',{assetId:'#id'},{
update: {
method: 'PUT' // this method issues a PUT request
}
});
});
Controller (for data list)
app.controller('fixedAssetListCtrl',['$scope','$location','$rootScope','Assets', function($scope, $location, $rootScope,Assets){
$scope.assets = Assets.query();
$scope.goEdit = function(id){
Assets.query({assetId:id}.edit);
$location.path('/editFixedAsset').search({assetId:id});
}
}]);
Controller (for edit)
app.controller('fixedAssetEditCtrl',['$scope','$location','$rootScope','Assets',
function($scope, $location, $rootScope, Assets){
var edit_id=$location.path('/editFixedAsset').search();
var assetId=parseInt(edit_id.assetId);
//window.alert($rootScope.assetId.ID);
$scope.editassets = Assets.query({assetId});// getting data
// console.log($scope.editassets);
$scope.asset = {};
$scope.updateFixedAsset =function(asset){
var faData ={
detailAssetCode:$scope.detailAssetCode,
detailDescription:$scope.detailDescription,
detailParchaseDate:$scope.detailParchaseDate,
detailSoldDate:$scope.detailSoldDate
} //end of faData
Assets.update({assetId},asset);
}
}]);
Laravel Routes
Route::group(array('prefix' => '/api'), function () {
Route::resource('assets', 'AssetController');
});
Controller
public function show($id){
$assets = FAModel::find($id);
$response[] = [
'detailAssetCode' => $assets->AssetCode,
'detailDescription' => $assets->Description,
'detailPurchaseDate' => $assets->PurchaseDate,
'detailoldDate' =>$assets->SoldDate,
];
return Response::json($response, 200);
}
public function update($id){
$FAModelObj = new FAModel;
$fixedAssetData = FAModel::find($id);
$FAModelObj->AssetCode = Input::json('detailAssetCode');
$FAModelObj->Description = Input::json('detailDescription');//need to be JSON object??
$FAModelObj->PurchaseDate = Input::json('detailPurchaseDate');
$FAModelObj->SoldDate = Input::json('detailSoldDate');
$FAModelObj->push();
return Response::json(array('success'=>true));
}
Can you find the problem??
How can I change to update the data? Thanks.
The problem is that you create a new instance to save data instead of existing one. That's why new row is created in database. Your code should be like that.
public function update($id){
$fixedAssetData = FAModel::find($id);
$fixedAssetData->AssetCode = Input::json('detailAssetCode');
$fixedAssetData->Description = Input::json('detailDescription');//need to be JSON object??
$fixedAssetData->PurchaseDate = Input::json('detailPurchaseDate');
$fixedAssetData->SoldDate = Input::json('detailSoldDate');
$fixedAssetData->push();
return Response::json(array('success'=>true));
}
Hope it will be useful for you.
Related
I've created a sample of my chart below using
nicholas bering, API Promise. I faked the $http data callback in my demo below.
My question is how to correctly access the draw() method of the chart after it is already displayed in the browser?
In my demo below, I create a google.visualization.DataView() so I can access the hideRows() method. Once that occurs, the documentation says I need to call on the draw() method to repaint the chart with the newly altered row information.
In this case I'm trying to let the user hide rows of items where the quantity being displayed is zero (row 2 "Olives" in my data). Once I get this working, I will let the user toggle other things but for now I'm trying to keep my question simple.
But this is where I get lost... the draw() method as I understand it should already exist on the original chart I created. How does one expose the draw() method of the original chart without having to poke at the DOM with a document.getElementById('myBarChart'). This seems so unlike everything Angular.
Here is my code:
<div ng-controller="ChartsController as ChartsController"
ng-init="ChartsController.init()">
<button ng-click="ChartsController.ToggleZeroDistributionOff()">No Zeros</button><br>
<div google-chart chart="chartMe" id="myBarChart" />
</div>
now my controller:
'use strict';
app.controller('ChartsController', ['$scope', '$http', '$q', 'googleChartApiPromise', function ($scope, $http, $q, googleChartApiPromise) {
this.name = "ChartsController";
this.$inject = ['$scope', '$q', '$http', 'googleChartApiPromise'];
$scope.chartMe = {};
this.init = function () {
// simulated $http callback data returned in promise
var dataPromise = {
"data": [
{"itemname": "Mushrooms", "qty": 13 },
{"itemname":"Onions", "qty": 11},
{"itemname":"Olives", "qty": 0},
{"itemname":"Zucchini", "qty": 1},
{"itemname": "Pepperoni", "qty": 27 }
]
}
// bind data and chart loading before building the my chart
$q.all({ data: dataPromise, api: googleChartApiPromise })
.then(apiLoadSuccess);
};
function apiLoadSuccess(result) {
$scope.chartMe.type = 'BarChart';
//create a new DataTable loaded with data from the HTTP response
$scope.chartMe.data = new google.visualization.DataTable();
$scope.chartMe.data.addColumn('string', 'Item Name/Units');
$scope.chartMe.data.addColumn('number', 'Qty');
// create an array to hold index of items
var aNoQty = [];
var aQty = [];
var aRows = [];
for (var i = 0; i < result.data.data.length; i++) {
var oData = [];
aRows.push(i);
oData[0] = result.data.data[i].itemname;
oData[1] = result.data.data[i].qty;
// which items quanity exist
if (result.data.data[i].qty > 0) {
aQty.push(i);
} else {
aNoQty.push(i);
};
// now add the row
$scope.chartMe.data.addRow(oData);
};
$scope.aNoQty = aNoQty;
$scope.aQty = aQty;
$scope.chartMe.options = {
title: "Item(s) Distributed",
isStacked: false,
displayExactValues: true,
};
};
this.ToggleZeroDistributionOff = function () {
$scope.chartMe.view = new google.visualization.DataView($scope.chartMe.data);
$scope.chartMe.view.hideRows($scope.aNoQty)
// this seems like the wrong way to attach to existing chart...
// i'm referring to using document.getElementById() - not very Angular !
// but how else to expose the draw() method ??
var myChart = new google.visualization.BarChart(document.getElementById('myBarChart'));
// now draw() method is expoised
myChart.draw($scope.chartMe.view.toDataTable(), $scope.chartMe.options)
}
}]);
Thanks in advance for any suggestions.
Thank you WhiteHat for your suggestion. It worked both ways but in my case found your first answer to be easier to work with.
I posted a complete solution below:
'use strict';
app.controller('ChartsController', ['$scope', '$http', '$q',
'googleChartApiPromise', function ($scope, $http, $q, googleChartApiPromise) {
this.name = "ChartsController";
this.$inject = ['$scope', '$q', '$http', 'googleChartApiPromise'];
$scope.chartMe = {};
this.init = function () {
// simulated $http callback data returned in promise
var dataPromise = {
"data": [
{"itemname": "Mushrooms", "qty": 13 },
{"itemname":"Onions", "qty": 11},
{"itemname":"Olives", "qty": 0},
{"itemname":"Zucchini", "qty": 1},
{"itemname": "Pepperoni", "qty": 27 }
]
}
// bind data and chart loading before building the my chart
$q.all({ data: dataPromise, api: googleChartApiPromise })
.then(apiLoadSuccess);
};
function apiLoadSuccess(result) {
$scope.chartMe.type = 'BarChart';
//create a new DataTable loaded with data from the HTTP response
$scope.chartMe.data = new google.visualization.DataTable();
$scope.chartMe.data.addColumn('string', 'Item Name/Units');
$scope.chartMe.data.addColumn('number', 'Qty');
// create an array to hold index of items
var aNoQty = [];
var aQty = [];
var aRows = [];
for (var i = 0; i < result.data.data.length; i++) {
var oData = [];
aRows.push(i);
oData[0] = result.data.data[i].itemname;
oData[1] = result.data.data[i].qty;
// which items quanity exist
if (result.data.data[i].qty > 0) {
aQty.push(i);
} else {
aNoQty.push(i);
};
// now add the row
$scope.chartMe.data.addRow(oData);
};
$scope.aNoQty = aNoQty;
$scope.aQty = aQty;
$scope.chartMe.options = {
title: "Item(s) Distributed",
isStacked: false,
displayExactValues: true,
};
// chart view used later
$scope.chartMe.view = new google.visualization.DataView($scope.chartMe.data);
// grab a reference to the chart
$scope.chartMe.myChart = new google.visualization.BarChart(document.getElementById('myBarChart'));
};
this.ToggleZeroDistributionOff = function () {
// $scope.chartMe.view = new google.visualization.DataView($scope.chartMe.data);
$scope.chartMe.view.hideRows($scope.aNoQty)
// draw() method exists so refresh with new view
$scope.chartMe.myChart.draw($scope.chartMe.view.toDataTable(), $scope.chartMe.options)
}
}]);
This worked for me and opened lots of new options.
Thanks! Another way to hide rows as a response to an input in the view, assuming that you don't have that much data, is to use ng-change and set
the value of the cells in your row(s)/column(s) to = null. You'll have to find all the cells that you want to set to null because you can't simply set the
whole row or column to null. One by one. The advantage is that you can stick to the simple way of using ng-google-charts. Again this might make things easier only for small charts. You can also write a function which does a push() to the table an put in the ng-change of your input to do insert data from the view. If you ng-change affects directly the DataTable, make a variable that stores the original values, that way you can hide and then restore columns or rows.
https://www.w3schools.com/angular/ng_ng-change.asp
Here is my issue:
The datatable plug-in only accepts an array I believe but my API returns an object with an array. I am trying to figure out if I need to extract this info (how?) or if the plug-in has some methods that do that for me (there is one):
//the datatable plugin expects the following JSON structure
[
{
"ID":"a5f415a7-3d4f-11e5-b52f-b82a72d52c35",
"Record":1,
"HostName":"SRX552P"
}
]
//my PHP server returns the following JSON structure:
{
"status":"success",
"message":"data retrieved",
"data":[
{
"ID":"a5f415a7-3d4f-11e5-b52f-b82a72d52c35",
"Record":1,
"HostName":"SRX552P"
}
]
}
var allData = null;
//this is my angularjs service where I am grabbing all the 'data':
function getAllData() {
dataservice.get('table001').then(function(data){
allData = data;
});
return allData;
}
//it looks like my issue is exactly what this post describes:
http://stackoverflow.com/questions/27797435/accessing-json-data-in-angularjs-datatables-using-dtoptions
//but applying ".withDataProp('data.data')" didn't work for me:
...
this.standardOptions = DTOptionsBuilder
.fromFnPromise(getAllData())
.withDataProp('data.data')
//.fromSource('api/tables/datatables.standard.json') //static data works fine!
//Add Bootstrap compatibility
.withDOM("<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
"t" +
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>")
.withBootstrap();
this.standardColumns = [
DTColumnBuilder.newColumn('ID'),
DTColumnBuilder.newColumn('Record'),
DTColumnBuilder.newColumn('HostName')
];
...
//this is the service
(function () {
'use strict';
angular.module('app.ipxtool').factory('dataservice', dataservice);
dataservice.$inject = ['$http', '$q'];
function dataservice($http, $q) {
var serviceBase = 'api/v1/';
var obj = {};
obj.get = function (q) {
return $http.get(serviceBase + q).then(success).catch(fail);
};
function success(results) {
if (results.data.status == "error") {
logger.error(results.data.message, '', 'Error'); //$response["data"] = null for errors;
}
if (results.data.status == "warning") {
logger.warning(results.data.message, '', 'Warning');
}
if (results.data.status == "success") {
logger.success(results.data.message, results.data.data, 'Success'); //$response["data"] = $rows;
}
return results.data;
}
function fail(e) {
return (e);
}
return obj;
};
})();
Using Fiddler I can see all the data being returned. Also I output the first array item as follows:
console.log("var allData: " + "[" + JSON.stringify(alldata.data[1]) + "]");
The solution to this issue was to add the following:
.fromFnPromise(function() {
return dataservice.get('table001');
})
Not sure why calling getAllData() didn't work. So finally I got this thing resolved. Thanks.
You can add [ and ] at the start and at the end of your output var in php page itself, so that it would return a proper JSON output. Since I also faced such issue earlier in Angular as it doesn't accept direct Object input, I used the above approach to convert it into full-fledged JSON.
Also add the below code at the top of your PHP page:
header('Content-Type: application/json');
So that, it'll return the content in JSON-formatted text.
request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;
var time = Math.floor((Date.now() - Date.parse($scope.cases[i].date_case_modified))/(60000*60*24));
$scope.cases.duration.push(time);
}
});
Inside the controller I am trying to tack on the cases.duration onto the cases object but it wont add it onto the object that is returned. Any ideas?
I think you just need to introduce a forEach as shown here:
request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;
angular.forEach($scope.cases, function (el) {
var time = Math.floor((Date.now() - Date.parse(el.date_case_modified))/(60000*60*24));
el.duration = time;
});
}
});
Hope this helps
I'm facing issues in returning data from Angular Service. Below is the service code....
app.service('Data',function(){
var accountList = [];
var currentAccount ='Test1'; //Initialization
var bookmarkAccount = function(accountName){
accountList.push(accountName);
}
var setPassingAccount = function(Account){
console.log('in Service : setting current account value to '+Account);
currentAccount = Account;
}
return{
bookmarkAccount: bookmarkAccount,
setPassingAccount: setPassingAccount,
currentAccount: currentAccount,
accountList: accountList
};
});
I'm able to access all methods/variables from 'Data' service except "currentAccount". Getting empty value, while accessing it from controller. Below is the controller code...
app.controller('BookmarkController',function(Data){
this.accountList = [];
this.accountList = Data.accountList;
this.account = Data.currentAccount; //ISSUE
Console.log('Account list object'+accountList);
Console.log('Current account selected :'+this.account);
}
I'm able to get all values in 'accountList', but getting empty 'currentAccount'. Can anyone please help on this.
I'm a newbie in AngularJS and have faced the issue.
Can I reinject my factory singleton object across all controllers, where it's been injected?
For example:
.factory('medicalCenterService', function(MedicalCenterResource) {
var medicalCenterService = {};
medicalCenterService.currentMedCenter = MedicalCenterResource.get();
medicalCenterService.reloadMedCenter = function() {
medicalCenterService.currentMedCenter = MedicalCenterResource.get();
return medicalCenterService.currentMedCenter;
};
medicalCenterService.updateMedicalCenter = function(medicalCenter) {
MedicalCenterResource.updateMedicalCenter(medicalCenter);
medicalCenterService.currentMedCenter = medicalCenter;
};
return medicalCenterService;
})
In MedicalCenterController I get singleton object with medical center when application starts:
function MedicalCenterController($scope, medicalCenterService) {
$scope.currentMedCenter = medicalCenterService.currentMedCenter;
}
But later I try to edit medical center fields (name, address, etc..) in AccountProfileController
function AccountProfileController($scope, medicalCenterService) {
$scope.currentMedCenter = medicalCenterService.currentMedCenter;
$scope.applyMedCenterChanges = function (currentMedCenter) {
medicalCenterService.updateMedicalCenter(currentMedCenter);
};
}
And what I'm expecting to have is the object with updated fields.
How to return a new instance of my singleton?
Do you want something like this?
.factory('MedicalCenter', function(MedicalCenterResource) {
var MedicalCenter = function () {
var center = MedicalCenterResource.get(),
update = function() {
MedicalCenterResource.updateMedicalCenter(center)
};
return {
center: center,
update: update
}
};
return MedicalCenter;
})
function MedicalCenterController($scope, MedicalCenter) {
center = new MedicalCenter();
$scope.currentMedCenter = center.center;
}
function AccountProfileController($scope, MedicalCenter) {
center = new MedicalCenter();
$scope.currentMedCenter = center.center;
$scope.applyMedCenterChanges = function () {
center.update();
};
}
Like you wrote in post services are Singletons and its good way to share data over services. However if you want to create new instance of factory/service, you can't do that but we can create list of objects in one service/factory where each list item represents different instance. Something like:
.factory('medicalCenterService', function(MedicalCenterResource) {
var medicalCenterServices = [
{ctrlName: 'MedicalCenterController',medicalCenterService: {/*....*/}},
{ctrlName: 'AccountProfileController',medicalCenterService: {/*....*/}},
];
//......
})