AngularJS UI-GRID: editDropdownOptionsFunction and async $http.get - javascript

I use ui-grid v3.2.9. I have grid with inline editing, one of editing cell - dropdown control. I want to get array for dropdown control every time when I click to this cells. I try to use editDropdownOptionsFunction to download json for dropdown:
columnDefs: [
{
name: 'serial',
displayName: 'Serial',
width: 100,
enableCellEdit: true,
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownIdLabel: 'id',
editDropdownValueLabel: 'id',
editDropdownOptionsFunction: function(rowEntity, colDef){
var res = [];
$http.get('index.php?r=docs/serialsjson2&recid=' + rowEntity.id)
.success(function (data) {
res = data;
});
return res;
}
},
],
But as I understand $http.get finished too late and no fills dropdownarray.
Help me please. How do I need to do request data from server to dropdown widget in moment click?

Loading the dropdown data happens after the data is returned into success function.Only means to get the data faster is retriving data in simple steps without more loops or query operations[re-factor].
If that doesn't happen you can just try adding spinner(loader) in http interceptor and disable dropdown untill data is populated.
There are lot of ways in implementing spinners and hideoverlays for dropdown.
Below is one example link
Spinner and Overlay

you need to return the promise from $http:
return $http.get('index.php?r=docs/serialsjson2&recid=' + rowEntity.id).then(function (data) {
return data;
});
Also use .then instead of .success----success is deprecated

Related

ExtJs 4.1.2 ComboBox Update or Reload Based on another ComboBox

I'd like to know a way of how to update the list values of a ExtJs ComboBox. For instance, I have two comboboxs.
One Combobox determine what values the another ComboBox should have. So, after selecting some of those,
I click the drowndown list (combobox) to see the values. But i dont get reflected.
change: function (combofirst, record) {
Ext.Ajax.request({
-- -- --
-- -- --
success: function (response) {
var combosecond = Ext.getCmp('defaultPackageType');
//I am unable to update the combosecond from below snippet.
combosecond.store = Ext.create('Ext.data.Store', {
fields: ['value', 'display'],
data: [
["N", "No"],
["A", "All accounts"]
] //json response
});
},
failure: function (record, action) {}
});
});
In short, how can I change the values of a ComboBox already has with ajax only.
Hope someone can help me
Thanks
I would also agree to the comment, that creating every time a new store and bind it to the combobox is not the optimal solution. I don't know really the reason why this should be done, but nevertheless here is a working example by using bindStore:
https://fiddle.sencha.com/#view/editor&fiddle/3ci0
Ext.create('Ext.form.field.ComboBox', {
// ...
listeners: {
change: {
fn: function (cb) {
Ext.Ajax.request({
url: 'https://jsonplaceholder.typicode.com/albums',
method: 'GET',
timeout: 60000,
success: function (response) {
var jsonResp = response.responseText;
let jsonObj = Ext.JSON.decode(jsonResp, true)
var combo2 = Ext.getCmp('myCombo2');
combo2.bindStore(Ext.create('Ext.data.Store', {
fields: ['id', 'title'],
data: jsonObj
}));
}
});
}
}
}
});
For selection of value 1 the data is loaded from a different url.
But I would think about whether a new proxy call is necessary and whether you can achieve your requirements by using filters or something else.

AngularJS Read From JSON Returning Nothing

I am building an application that has a button that loads up help based on IDs from the JSON, when I have the JSON in the controller.js I see it on the web page but if I do it externally I do not see anything. I feel I am missing something extremely simple but may be over looking it. Any ideas?
controllerNEW.js
app.factory("UserService", function($rootScope, $http){
function getFile(){
return $http.get('stat.json').then(function(data) {
return data;
});
}
return{statErr: getFile,
//hide the displayed tooltip based on its id
hideTooltip: function(key, scopes, data)
{
controllerOLD.js
app.factory("UserService", function($rootScope){
return{
statErr: [
{
selector: "#userEmail",
fieldTitle: "Email",
placement: "right",
content: "test",
offsetTop: 500,
correctKey: "#test",
inErrorList: false
},
{
selector: "#userId",
fieldId: "id1",
fieldTitle: "ID",
placement: "right",
content: " number should contain 4 zeroes '...0000...'",
offsetTop: 500,
correctKey: "0000",
inErrorList: false
}
],
//hide the displayed tooltip based on its id
hideTooltip: function(key, scopes, data)
{
The issue is getFile() returns a promise not the data itself. It is true that you have a .then(function(data) {return data; });, but, .then() also returns a promise.
So to fix this issue, in your actual code, after you call getFile() you also need to add .then() to have access to your data:
getFile().then(function(data){
// now you have access to your data
})
you need to access the data object in the response object.
example:
var jsonResponse = $http.get('content.json').then(function(response) {
return response.data;
});
In your example, data is the whole response to your request, including headers and status. To see your data from the 'stat.json' file, you would access the data object of your data. So, the change is.
function getFile(){
return $http.get('stat.json').then(function(data) {
return data.data;
});
}
you can try something like this
$http.get('stat.json').then(function(result){
$scope.dataset = result.data
console.log($scope.dataset)
},function(error){
console.log(error)
})

How to Paginate dynamic AngularJS table?

How do I get pagination with ng-table-dynamic and $http working?
HTML specification of the table is
<table class="table-bonds table table-bordered table-hover table-striped"
export-csv="csv"
separator=","
show-filter="true"
ng-table-dynamic="bondsTable.bondsDataParams with bondsTable.bondsDataCols">
<tr ng-repeat="row in $data">
<td class="hand"
ng-repeat="col in $columns">{{::row.node[col.field]}}</td>
</tr>
The table creation code is:
self.bondsDataParams = new NgTableParams({
page: 1, // show first page
count: 5 // count per page
}, {
filterDelay: 0,
total: 0,
getData: function (params) {
return $http(bondsDataRemote).then(function successCallback(response) {
// http://codepen.io/christianacca/pen/mJoGPE for total setting example.
params.total(response.data.nodes.length);
return response.data.nodes;
}, function errorCallback(response) {
});
}
});
AngularJS 1.5.8
This is an excellent directive for pagination have a look at it . It has lots of options and its easy to use.
The main problem was mixing up loading the data via ajax and not supporting the filtering/pagination on the server side of the request.
Either provide all the data up-front so that the table can filter, or fully support the pagination, sorting and filtering on the server side.
Option 1. Load the data before hand. I used this option because my dataset is not that big and it seemed like the easiest way to allow people to use all the permutations of filtering sorting and downloading.
No total value is required here. The data is all loaded.
var Api = $resource('/green-bonds.json');
// Or just load all the data at once to enable in-page filtering, sorting & downloading.
Api.get({page: "1", count: "10000"}).$promise.then(function (data) {
self.bondsDataParams = new NgTableParams({count: 25}, {
dataset: data.results
})
});
Or fully support the lazy loading data API and set total. Uses getData: rather than just setting dataset.
var Api = $resource('/green-bonds.json');
this.bondsDataParams = new NgTableParams({}, {
getData: function (params) {
return Api.get(params.url()).$promise.then(function (data) {
params.total(data.count);
return data.results;
});
}
});
Note 1: By default $resource expects an object .get() for object, .query() for array. Also see isArray:. I didn't get this to work.
Note 2: params.url() provides $resource with the ng-table params. e.g. {page: "1", count: "10"}

Using Select 2 with ASP.NET MVC

I am working on an ASP.NET MVC 4 app. In my app, I'm trying to replace my drop down lists with the Select 2 plugin. Currently, I'm having problems loading data from my ASP.NET MVC controller. My controller looks like this:
public class MyController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<MyItem>))]
public IHttpActionResult Get(string startsWith)
{
IEnumerable<MyItem> results = MyItem.LoadAll();
List<MyItem> temp = results.ToList<MyItem>();
var filtered = temp.Where(r => r.Name.ToLower().StartsWith(startsWith.ToLower());
return Ok(filtered);
}
}
When I set a breakpoint in this code, I notice that startsWith does not have a value The fact that the breakpoint is being hit means (I think) my url property below is set correct. However, I'm not sure why startsWith is not set. I'm calling it from Select 2 using the following JavaScript:
function formatItem(item) {
console.log(item);
}
function formatSelectedItem(item) {
console.log(item);
}
$('#mySelect').select2({
placeholder: 'Search for an item',
minimumInputLength: 3,
ajax: {
url: '/api/my',
dataType: 'jsonp',
quietMillis: 150,
data: function (term, page) {
return {
startsWith: term
};
},
results: function (data, page) {
return { results: data };
}
},
formatResult: formatItem,
formatSelection: formatSelectedItem
});
When this code runs, the only thing I see in the select 2 drop down list is Loading failed. However, I know my api is getting called. I can see in fiddler that a 200 is coming back. I can even see the JSON results, which look like this:
[
{"Id":1,"TypeId":2,"Name":"Test", "CreatedOn":"2013-07-20T15:10:31.67","CreatedBy":1},{"Id":2,"TypeId":2,"Name":"Another Item","CreatedOn":"2013-07-21T16:10:31.67","CreatedBy":1}
]
I do not understand why this isn't working.
From the documentation:
Select2 provides some shortcuts that make it easy to access local data
stored in an array...
... such an array must have "id" and "text" keys.
Your json object does not contain "id" or "text" keys :) This should work though i have not tested it:
results: function (data, page) {
return { results: data, id: 'Id', text: 'Name' }
}
There's further documentation following the link on alternative key binding... I believe thats where your problem lies.
Hopefully this helps.

AngularUI select2 AJAX set via model

I'm using AngularUI's ui-select2 directive with AJAX.
Here's what I've got in my view:
<label>Group: <input ng-model="group" ui-select2="select2GroupConfig"></label>
Here's what I have in my model:
$scope.select2GroupConfig = {
ajax: {
url: 'theURL',
data: function (term, page)
{
return { q: term };
},
results: function (data, page)
{
return { results: data };
}
}
};
This works as expected.
My question: How can I update the value via the model?
I tried:
$scope.group = 'some group';
I also tried using an object:
$scope.group = { id: 32, text: 'some group'};
but that doesn't either work.
How do you update a select2 that uses AJAX, via the model?
Turns out you can set it to an object, but only after ui-select2 runs; I was trying to give it an initial value.
So, instead of using the regular model, you have to use select2's initSelection function:
$scope.group = 'Dummy Content';
$scope.select2GroupConfig.initSelection = function ( el, fn ) {
fn({ id: 2, text: 'Some group' });
}
Note that you have to give the input an initial value, otherwise initSelection is never called. That's why I'm just setting it to some dummy content.
This works, but it feels like a hack.
Does anybody have any better ideas?
If you have initSelection setup, you can pass just the ID and the directive will pull up the entire row object.
This will also allow you to set the value when the page loads to just the ID too.
If you don't want to use initSelection you can set the entire row (object) as the value and select2 will update accordingly. It all depends on your use-case however.

Categories

Resources