Updating cell data in ui-grid without page refresh - angularjs

I have a table that I made using ui-grid. The table displays information about a list of news stories. In the final column, I am giving the user the ability to edit, delete, and/or make a news story.
Everything seems to be working fine with that - I am able to have a modal pop up, and after entering in the required information, I can see my data change on the server. If I refresh the page, I can also see my data change on the table. However, I would like the cell data to change without page refresh. It doesn't seem to be binding to my news data.
Here is the ui-grid:
$scope.news = getAdminNews.results;
/**
* ui-grid implementation
*/
$scope.gridOptions = {
data: 'news',
enableColumnResizing: true,
enableFiltering: true,
enableGridMenu: false,
enableColumnMenus: false,
paginationPageSizes: [25,50,75],
paginationPageSize: 25,
rowHeight: 75
};
$scope.gridOptions.columnDefs = [{
displayName: 'Title',
field: 'title.rendered',
filterCellFiltered: true,
sortCellFiltered: true,
width: '20%'
}, {
displayName: 'Body',
field: 'body',
width: '20%'
}, {
displayName: 'Created',
field: 'created',
type: 'date',
cellFilter: 'date:"yyyy-MM-dd"',
filterCellFiltered: true,
sortCellFiltered: true,
width: '20%',
sort: {
priority: 0
}
},
{
displayName: 'Actions',
displayName: 'Actions',
width: '20%',
enableSorting: false,
enableFiltering: false,
field: 'actions',
cellTemplate: 'table-cell-actions'
}
];
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridApi = gridApi;
};
And one part of my controller which is working successfully:
$scope.newPost = function() {
ngDialog.openConfirm({
template: 'modalPostNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
var newPost = {
"id": 0,
"title": $scope.newPostForm.title
}
AdminNews.save(newPost);
toaster.pop('success', 'Updated', 'News item updated successfully.');
});
}

I needed to update my $scope.news data that ui-grid was populating the table with. Here is what my controller looks like now:
$scope.newPost = function() {
ngDialog.openConfirm({
template: 'modalPostNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
var newPost = {
"id": 0,
"title": $scope.newPostForm.title
}
AdminNews.save(newPost).$promise.then(function(response) {
var myObj = {
"id": response.data.id,
"title": {
"rendered": response.data.title
}
}
$scope.news.push(myObj);
});
toaster.pop('success', 'Updated', 'News item updated successfully.');
});
}

Related

populate Dropdownlist in ui grid dynamically

i have spent lots of hours finding a solution but no success every time i am finding a solution it ends up with static data not from any web API or database. i want dynamic data to be populated in drop down list in UI grid. i have read in one blog in which guy was saying for dynamic data we have to use editDropdownRowEntityOptionsArrayPath but i did not find any useful solution. any one can provide any useful information than i will be vary thankful. thanks in advance. this is what i have done.
$scope.listOptions = []; $scope.ddlist = [];
$http.get('http://localhost:26413/api/MenuVDN/GetVDNList')
.then(function (data) {
$scope.listOptions = data;
$scope.ddlist = $scope.listOptions.data.Table;
console.log($scope.ddlist);
})
$scope.gridOptions = {
enableColumnResizing: true,
enableSorting: true,
enableCellSelection: true,
canSelectRows: true,
// enableCellEdit: true,
columnDefs: [
{ field: 'NameEn', displayName: ' Menu Name', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'asc' }, width: '25%' },
{ field: 'id', displayName: 'ID' },
{ field: 'language', displayName: 'VDN Language', grouping: { groupPriority: 1 }, sort: { priority: 1, direction: 'asc' } },
{ field: 'vdnname', displayName: 'VDN Name' },
{
field: 'vdnnum', displayName: 'VDN Number',
editableCellTemplate: 'ui-grid/dropdownEditor',
// editDropdownIdLabel: 'id',
editDropdownValueLabel: 'value',
// enableFocusedCellEdit: true,
enableCellEditOnFocus :true,
enableCellEdit: true,
editType: 'dropdown',
editDropdownRowEntityOptionsArrayPath : $scope.ddlist
// , cellEditableCondition: function( $scope ) { return true; }
}
]
};
plus i am getting response from webapi in json format like this.
{"Table":[{"id":2,"value":"AR-BOOKING-NEW (7101)"},
{"id":3,"value":"EN-BOOKIN-NEW (7102)"},
{"id":4,"value":"AR-BOOKING-CANCEL (7103)"},
{"id":5,"value":"EN-BOOKING-CANCEL (7104)"},
{"id":6,"value":"AR-BOOKING-MODIFY (7105)"}]}
$scope.columns = completedFiles.columns;
$scope.rows = completedFiles.rows;
//prepare custom column for ui-grid
var customColumns = [];
angular.forEach($scope.columns, function(column) {
customColumns.push({
field : column.fieldName,
displayName : column.displayName,
editable : column.editable,
dataType : column.dataType,
});
}
});
angular.forEach(customColumns, function(customColumn) {
customColumn['width'] = 200;
if (customColumn.dataType === 'dropDown') {
customColumn['cellTemplate'] = "<div class='ui-grid-cell-contents' id='col-description'><select class="form-control" data-ng-options="item in grid.appScope.arrayName track by item" ><option value="" selected hidden />/></select></div>";
customColumn['width'] = 180;
}
});
You can create custom template like above and after that just assign in $scope.gridOptions customColumns to columnDefs rather then defining the column definition there.

Select some entities from row in ui-grid

I have in my grid sometimes few columns, I hide some that only two are visible. I want to select rows only with these two entities(visible) and pass them to array. In this example Date and Result. Is there specific method to do this? Because when I use
vm.chartData.push($scope.gridApi.selection.getSelectedRows()) in chartData array I have got all entities.
This is my controller code.
(function () { "use strict";
angular.module("app")
.controller("grid", grid);
function grid($scope) {
var vm = this;
vm.chartData = [];
$scope.gridOptions =
{
enableGridMenu: true,
enableSorting: true,
enableRowSelection: true,
selectionRowHeaderWidth: 35,
enableSelectAll: true,
multiSelect: true,
columnDefs: [
{ name: 'Trial', field: 'Trial' },
{ name: 'Date', field: 'Date', type: "date", cellFilter: "date:'dd-MM-yyyy HH:mm'" },
{ name: 'Result', field: 'Result'}
],
data: [
//example of row entities
{
"Trial": "Weight",
"Date": "2015-02-03T05:49:54.850Z",
"Result": 60
}
]
};
$scope.pushAll = function () {
//this line returns all three entities
vm.chartData.push($scope.gridApi.selection.getSelectedRows());
};
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
};
}

nested kendo grid - binding detailInit with data from service call

I have a angular directive which returns the kendo grid data source values (which is gridDataDisplayed). With the same data source, i have to bind it to a nested grid in detailInit.
scope.gridsource = new kendo.data.DataSource({
pageSize: options.pSize,
transport: {
read: function (options) {
scope.getDataMethod({ pageDetails: options }).then(function (gridDataDisplayed) {
options.success(gridDataDisplayed);
}, function (error) {
//error
});
}
},
detailInit: detailInitMethod
});
In the detailInitMethod i have the use the same data returned from service call and display only few columns from "gridDataDisplayed". How can i bind this to nested grid?
In my directive the template code is:
template: '<div><kendo-grid k-options="gridOptions" k-data-source="gridDataSource"></kendo-grid></div>',
Thanks in advance.
You can use the detail-template directive. Here is how:
<div ng-controller="MyCtrl">
<kendo-grid options="mainGridOptions" k-data-source="gridDataSource">
<div k-detail-template>
<div kendo-grid k-options="detailGridOptions"></div>
</div>
</kendo-grid>
</div>
<script>
angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", function($scope){
$scope.gridDataSource = {
type: "odata",
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
},
pageSize: 5,
serverPaging: true,
serverSorting: true
};
$scope.mainGridOptions = {
sortable: true,
pageable: true,
dataBound: function() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [{
field: "FirstName",
title: "First Name",
width: "120px"
},{
field: "LastName",
title: "Last Name",
width: "120px"
}]
};
$scope.detailGridOptions = {
scrollable: false,
sortable: true,
dataSource: $scope.gridDataSource,
pageable: true,
columns: [
{ field: "City", title:"City", width: "56px" },
{ field: "Address", title:"Address", width: "110px" }
]
};
});
</script>
And a live demo: http://dojo.telerik.com/#korchev/UFIqa

Populate ng-grid by another grid selection

I am trying to populate a ng-grid based on the JSON array returned from a selection of a first ng-grid. As of right now I can get the JSON array displayed onto the screen but I cannot navigate deeper into the JSON array or get anything to display in the second grid. I have the controller code attached and the plnkr can be found at http://plnkr.co/edit/nULoI4?p=info.
'use strict';
function ArticleDataCtrl($rootScope, $scope, articleDataService) {
articleDataService
.getArticles()
.then(
function(articles) {
$rootScope.articles = articles;
$scope.articleGridItems = articles.data.specialMerchandise.specialMerItem;
});
$scope.articleGrid = {
data: 'articleGridItems',
showGroupPanel: false,
multiSelect: true,
checkboxHeaderTemplate: '<input class="ngSelectionHeader" type="checkbox" ng-click="getDeliveryLocations()" ng-model="allSelected" ng-change="toggleSelectAll(allSelected)"/>',
showSelectionCheckbox: true,
selectWithCheckboxOnly: true,
enableColumnResize: true,
selectedItems: [],
columnDefs: [{
field: 'soMerArticleNbr',
displayName: 'Article'
}, {
field: 'soMerOrdQty',
displayName: 'Qty'
}, {
field: 'soArtDeliveryCode',
displayName: 'Delivery Code'
}, {
field: 'dsgnSysRecDesc',
displayName: 'Description'
}]
};
//This is not being called on header template click
$scope.getDeliveryLocations = function() {
$scope.deliveryLocationData = $scope.commonDeliveryLocations;
};
$scope.selections = $scope.articleGrid.selectedItems;
var jsonObject = JSON.stringify($scope.selections);
//Thought a json problem occured here...was wrong
$scope.test = jsonObject.deliveryLocations;
$scope.deliveryGrid = {
data: 'selections',
showGroupPanel: false,
multiSelect: false,
columnDefs: [{
displayName: 'Delivery Methods'
}]
};
}
myApp.controller('ArticleDataCtrl', ['$rootScope', '$scope',
'articleDataService', ArticleDataCtrl
]);
So instead of trying to use angular's built in checkboxes I used my own with a custom method on ng-click. Here is the code and the plunker demonstrating the functionality is http://plnkr.co/edit/nULoI4?p=info.
'use strict';
function ArticleDataCtrl($rootScope, $scope, articleDataService) {
articleDataService
.getArticles()
.then(
function(articles) {
$rootScope.articles = articles;
$scope.articleGridItems = articles.data.specialMerchandise.specialMerItem;
});
$scope.articleGrid = {
data: 'articleGridItems',
showGroupPanel: false,
multiSelect: false,
enableColumnResize: true,
selectWithCheckboxOnly: true,
columnDefs: [{
/*
headerCellTemplate: myHeaderCellTemplate,
*/
cellTemplate: '<input id="checkSlave" name="articleCheckBox" ng-checked="master" type="checkbox" ng-click="getDeliveryLocation(row.entity)" />'
}, {
field: 'soMerArticleNbr',
displayName: 'Article'
}, {
field: 'soMerOrdQty',
displayName: 'Qty'
}, {
field: 'soMerUOIDesc',
displayName: 'UOM'
}, {
field: 'soArtDeliveryCode',
displayName: 'Delivery Code'
}, {
field: 'soMerShrtMerDesc',
displayName: 'Description'
}, {
field: 'soMerDesc',
displayName: 'Vendor'
}]
};
$scope.getDeliveryLocation = function(deliveryLocation) {
$scope.deliveryLocationData = deliveryLocation.deliveryLocation;
for (var i = 0; i < $scope.deliveryLocationData.length; i++) {
var locationId = $scope.deliveryLocationData[i].dlvryLocId;
var locationDesc = $scope.deliveryLocationData[i].dlveryLocDesc;
$scope.deliveryLocationData[i].dlvryLocId = locationId + locationDesc;
}
return $scope.deliveryLocationData;
};
return $scope.deliveryLocationData;
};
$scope.deliveryGrid = {
data: 'deliveryLocationData',
showGroupPanel: false,
multiSelect: false,
columnDefs: [{
field: 'dlvryLocId',
displayName: 'Delivery Methods'
}]
};
$scope.customerGroup = {
value: 'DIY'
};
}
myApp.controller('ArticleDataCtrl', ['$rootScope', '$scope',
'articleDataService', ArticleDataCtrl
]);

how to use ng-grid to update cells with $http?

I am new to angular and am trying to make a CRUD app with the ng-grid plugin. I found an example from the web that gets me the info I need, but not a good explanation on how to update the info using a REST route. Here is the code:
var cellEditableTemplate = "";
// Configure ng-grid
$scope.gridOptions = {
data: 'myData',
enableCellEdit: true,
multiSelect: false,
columnDefs: [
{ field: 'Id', displayName: 'Id' },
{ field: 'Name', displayName: 'Name', enableCellEdit: true, editableCellTemplate: cellEditableTemplate },
{ field: 'Description', displayName: 'Description', enableCellEdit: true, editableCellTemplate: cellEditableTemplate }
]
};
// Update Entity on the server side
$scope.updateEntity = function (column, row) {
console.log(row.entity);
console.log(column.field);
// code for saving data to the server...
// row.entity.$update() ... <- the simple case
}
How do I use the following from the example to update my model?
row.entity.$update()
Inject $http into your controller.
Then in your $scope.updateEntity:
$scope.updateEntity = function() {
$http.get('getDataFromServerUrl').success(function(data) {
//update data
$scope.gridOptions.data = data;
}).error(function(err) {
console.log('Error getting data', err);
});
}
and then your data will be updated, as $http activate the $digest cycle.

Resources