ng grid passing variables in cellTemplate - angularjs

I have an ng-grid that is connected to a SharePoint list. The SharePoint list is returning an ID number instead of the user name when I am trying to populate a field with a user name.
I have a function that is converting the ID to a user name.
$scope.getUserName = function (user) {
var userId = user;
$Service.getUserById($scope, userId).done(function (data) {
$scope.userName = data.d.Title;
})
}
When I am trying to call the function in a "cellTemplate", I can't send the ID variable to the function.
$scope.gridOptions = {
loading: true,
enableSorting: true,
enableFullRowSelection: true,
enableRowHeaderSelection: false,
showGroupPanel: true,
columnDefs: [
{ name: "Admin", field: "AdministratorId" },
{ name: "User", field: "ApprovedById" },
{ name: "SuperUser", cellTemplate: '<div>{{grid.appScope.getUserName(<pass the id variable here>)}}{{grid.appScope.userName}}</div>' }
],
data: 'gridData'
};
How do I get the userID from 'gridData' and send it to my function?
Update: The REST call I am using.
function getListItem(listName) {
var deferred = $.Deferred();
// query the list in the host web
var url = SPAppWebUrl + "/_api/SP.AppContextSite(#target)" +
"/web/lists/getbytitle('" + listName + "')/items?" +
"#target='" + SPHostUrl + "'";
$.ajax({
url: url,
type: "GET",
headers: { "Accept": "application/json;odata=verbose" }, // return data format
success: onGetEntriesSuccess,
error: onoDataCallFailure
});
function onGetEntriesSuccess(data) {
deferred.resolve(data.d);
}
function onoDataCallFailure(data, errorcode, errorMessage) {
deferred.reject("Error: " + errorMessage);
}
return deferred;}

Your Code:
cellTemplate:
'<div>{{grid.appScope.getUserName(**<pass the id variable here>**)}}{{grid.appScope.userName}}</div>'
Pass id like this : row.entity.Id // this id is available in your raw data.
and now code is:
cellTemplate: '<div>{{grid.appScope.getUserName(row.entity.Id)}}{{grid.appScope.userName}}</div>'

Related

How to post an array to mvc controller

I want to post java script object to mvc controller
$(document).ready(function () {
var table = $('#my_table_1').DataTable({
"paging": true,
"ordering": true,
"info": true,
"search": true,
"pageLength": 100
});
var d = '';
var data3 = table.on('search.dt', function () {
//number of filtered rows
// console.log(table.rows({ filter: 'applied' }).nodes().length);
//filtered rows data as arrays
d = table.rows({ filter: 'applied' }).data()
});
console.log(table.rows({ filter: 'applied' }).data());
$('#excel2').click(function (e) {
//var data3 = table.on('search.dt', function () {
// console.log(table.rows({ filter: 'applied' }).data());
// console.log(data3);
//});
console.log(d);
$.ajax({
url: '/Administrator/TestDownload',
type: 'POST',
data: {data:d},
cache: false
}).done(function (response) {
alert(d);
});
});
});
//Controller code:
public JsonResult TestDownload(String[] data)
{
return Json(data,JsonRequestBehavior.AllowGet);
}
I am getting null in controller as a data parameter
Expected: Want to get data object from view to controller as a parameter in controller.
Actual: Data parameter in controller is null
You must check your d variable correct array format.
I tested in my side with var d = ["test",2,3] and in controller it get correct data.
$('#excel2').click(function (e) {
//var data3 = table.on('search.dt', function () {
// console.log(table.rows({ filter: 'applied' }).data());
// console.log(data3);
//});
d = ["test",2,3]
console.log(d);
$.ajax({
url: '/Administrator/TestDownload',
type: 'POST',
data: {data:d},
cache: false
}).done(function (response) {
alert(d);
});
});
});
An example that works:
var test = ["This", "is", "a", "test"];
$.ajax({
type: "POST",
traditional: true,
url: "Administrator/TestDownload",
data: { array: test }
}
});
The controller(in VB.net):
Function TestDownload(array As String()) As ActionResult
//do something
End Function
Why not try stringifying the data and setting the contentType
$.ajax({
url: '/Administrator/TestDownload',
data: JSON.stringify({data:d}), // use JSON stringify
type: 'POST',
contentType: "application/json; charset=utf-8", //add this
cache: false
}).done(function (response) {
alert(d);
});
});

Angular: How to return value from service method to scope variable

I have following service method with return statement.
this.partnersListForAutocomplete = function (container, options) {
$("#autocompletePartners").kendoAutoComplete({
dataSource : {
type: "json",
serverFiltering: true,
transport: {
read: function (options) {
console.log("List");
console.log(options.data);
requestParams = {
"entityName": "dvd",
"page": 1,
"pageSize": 20,
"filter": options.data.filter,
"sort": [
{
"field": "name",
"ord": "asc"
}
]
};
ApiService.doHttpRequest(
"POST",
$rootScope.apiBaseUrl + "partner/search",
requestParams
)
.success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
}
}
},
dataTextField: "name" ,
dataValueField: "id",
filter: "contains",
minLength: 1,
change : function (e) {
// I WANT RETURN IT
return "test";
},
select : function (e) {
// I WANT RETURN IT
return "test";
}
});
};
Which is called by this code from controller method:
selectedPartnerId = GlobalHelperService.partnersListForAutocomplete();
$scope.projectDetail.test = selectedPartnerId;
Problem is that returned value is not passed into selected scope.
How can i solve it please?
Note: Method for autocomplete is assync.
Thanks for any help.
You have a couple of options that I can think of from the top of my head:
You could return a promise from the partnersListForAutocomplete() method, and then inside your controller you would then do something like the following pseudocode:
GlobalHelperService.partnersListForAutocomplete()
.then(function(response) {
$scope.projectDetail.test = response;
});
Or, accept a callback to your partnersListForAutocomplete() method, and then inside your controller you would then do something like the following pseudocode:
GlobalHelperService.partnersListForAutocomplete(function(response) {
$scope.projectDetail.test = response;
});

Preload entire FuelUx tree in one ajax call

I am trying to use the FuelEx tree control. I do not want to load each node on the tree when the user selects the node. I would rather load the entire tree structure at the point the pages loads. I have a controller already built that builds the correct json for my entire tree.
Is there an example of how to preload the entire structure?
I am currently attempting to use the following as a starting point. I will convert it a Datasource object once I get it working correctly.
$('#myTree').tree({
dataSource: function(options, callback){
var self = this;
var param = null;
if ("type" in options && options.type == "folder") {
if ("dataAttributes" in options && "children" in options.dataAttributes) {
param = options.dataAttributes["id"];
}
}
debugger;
if (param != null) {
$.ajax({
url: "/bundle-picker-data",
//data: 'id=' + param,
type: 'GET',
dataType: 'json',
success: function (response) {
if (response.status == "OK")
callback({ data: response.data })
},
error: function (response) {
console.log(response);
}
})
}
setTimeout(function () {
callback({ data: [
{ name: 'Ascending and Descending', type: 'folder', dataAttributes: { id: 'folder1' } },
{ name: 'Sky and Water I (with custom icon)', type: 'item', dataAttributes: { id: 'item1', 'data-icon': 'glyphicon glyphicon-file' } },
{ name: 'Drawing Hands', type: 'folder', dataAttributes: { id: 'folder2' } },
{ name: 'Waterfall', type: 'item', dataAttributes: { id: 'item2' } },
{ name: 'Belvedere', type: 'folder', dataAttributes: { id: 'folder3' } },
{ name: 'Relativity (with custom icon)', type: 'item', dataAttributes: { id: 'item3', 'data-icon': 'glyphicon glyphicon-picture' } },
{ name: 'House of Stairs', type: 'folder', dataAttributes: { id: 'folder4' } },
{ name: 'Convex and Concave', type: 'item', dataAttributes: { id: 'item4' } }
]});
}, 400);
},
multiSelect: true,
cacheItems: true,
folderSelect: false,
});
$('#tree-selected-items').on('click', function () {
console.log("selected items: ", $('#MyTree').tree('selectedItems'));
});
$('#myTree').on('loaded', function (evt, data) {
console.log('tree content loaded');
});
$('#myTree').on('opened', function (evt, data) {
console.log('sub-folder opened: ', data);
});
$('#myTree').on('closed', function (evt, data) {
console.log('sub-folder closed: ', data);
});
$('#myTree').on('selected', function (evt, data) {
console.log('item selected: ', data);
});
Thanks,
Greg
You do not have to use the dataSource function to call an external API each time. You can call the external API the first time dataSource is run and return the top level folders in the callback's data object. Then, the next time, do not make the ajax request and index into the collection of all items object based on the folder opened.
If that was unclear, load the object with all the tree information once at the beginning and grab whatever children you need out of it when a folder is opened based on that folder's attributes.
You have to load items each time--there is no other way with this control, but the items can be cached in memory and do not require an external network request.

ExtJs Add Json Data

I am facing problem in ExtJs. OnClick function it should load data for one time. But it is replicating the same data on every click.
Here is my code:
function onselectionchange()
{
jQuery.ajax({
type: "POST",
url: "/Maintainer/getfolders",
data: null,
contentType: "application/json; charset=utf-8",
async: true,
success: function (result) {
var store = Ext.getCmp('gridpanel').getStore();
store.loadData(result, true);
},
error: function (p_Result) {
var error = "Error on controller: \"" + p_Controller + "\" in function: \"" + p_ControllerFunction + "\" statusText: \"" + p_Result.statusText;
alert(error);
},
traditional: true
});
}
function onselectionchange()
{
if(clickonce == "")
{
ajax({
type: "POST",
url: "/url",
data: null,
contentType: "application/json; charset=utf-8",
async: true,
success: function (result) {
enter code here
clickonce = 1;
}
});
}
else
{
alert("already selected once");
}
}
What i'am doing here is creating a global variable with clickonce. When you first click on the button the json will get uploaded and the flag on this variable will set to 1 hence it won't be populated again.

Move Ajax respose data to store in Sencha touch

how to add or save data that getting from ajax request to store or to model sencha touch 2
I have controller, store and a model. Ext.Ajax.request(); is called from controller and when it was successful I want move that data to store in json format
Ext.define('Myapp.controller.HomeController', {
extend: 'Ext.app.Controller',
config: {
control: {
"#homepage_id": {
show: 'onHomepage_idShow'
}
}
},
onHomepage_idShow: function (component, eOpts) {
var token = localStorage.getItem('Token'); //**************************************
console.log('test home', token);
var customHeaders = {
'Content-Type': 'application/json; charset=utf-8',
'ApiAuth': token
};
this.callAjax(customHeaders);
},
callAjax: function (headers) {
var customHeaders = headers;
Ext.Ajax.request({
url: 'http://localhost:9098/Folder/json/Get',
params: Ext.util.JSON.encode({
folderId: 0
}),
method: 'POST',
headers: customHeaders,
success: function (response) {
var decode_text = Ext.decode(response.responseText);
/*I want to add decode_text to a store from this contoller..*/
//var storez = Ext.data.StoreManager.lookup('commomStore_id');//****************
//this.getDataList().setStore(storez);
console.log(storez);
// process server response here
},
failure: function (response, opts) {
Ext.Msg.alert('Error', 'Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
My Store:
Ext.define('Myapp.store.CommonStore', {
extend: 'Ext.data.Store',
requires: [
'Myapp.model.AuthTokenmodel'],
config: {
autoLoad: true,
model: 'Myapp.model.AuthTokenmodel',
storeId: 'commonStote_id',
proxy: {
type: 'localstorage',
id: 'commomStore_id',
reader: {
type: 'json'
}
},
fields: [{
name: 'authtoken'
}]
}
});
For that you have to parse your response and create Myapp.model.AuthTokenmodel objects out of it and then add those objects to your store using add method.
BTW if your response is in JSOn format you should parse it to JSON instead of text like this:
var respObj = Ext.JSON.decode(response.responseText);
console.log(respObj);
then create model objects using respObj data and add those to store:
var storez = Ext.data.StoreManager.lookup('commomStore_id');
storez.add(Ext.create('Myapp.model.AuthTokenmodel', {authtoken : respObj.authToken}));
Ext.getStore('commomStore_id').loadData(decode_text);

Resources