I am using Datatables to show data. When I click on a row, I want to work on the data and then do databinding to show these data. Here is the code I have for the datatable event :
table.on( 'select', function ( e, dt, type, indexes ) {
$scope.siege = {
economique: 30,
affaire: 30,
premiere: 30
};
if ( type === 'row' ) {
var avion = table.rows( indexes ).data()[0];
$scope.getConfiguration(avion);
// do something with the ID of the selected items
}
} );
As you can see, for the example, I want to bind data to $scope.siege but it doesn't work and there is nothing prompt in the console.
However, if I put :
$scope.siege = {
economique: 30,
affaire: 30,
premiere: 30
};
Somewhere else in the controller it works.
Thank you for your help.
Try to put a $scope.$apply .. cause it let angular knows that you need to refresh your $scope (if you're outside angular events) .. something like:
table.on( 'select', function ( e, dt, type, indexes ) {
$scope.siege = {
economique: 30,
affaire: 30,
premiere: 30
};
if ( type === 'row' ) {
$cope.$apply(function(){
var avion = table.rows( indexes ).data()[0];
$scope.getConfiguration(avion);
// do something with the ID of the selected items
})
}
} );
Related
The example I would like to replicate is this: https://jsfiddle.net/bindrid/hpkqxto6/ . I need to load data from the server, form a grouping of them and when selecting one item from one group all other items inside this particular group would become disabled. The difference is that I must load data from the server using an ajax call inside select2, instead of listing the < option > elements inside the select element and form a grouping this way. I have trouble selecting all available items in the dropdown list during the javascript manipulation in order to disable items from the same group (line 29 in the above example fails due to there being no < option > elements in html, instead I think they are loaded later and javascript is not able to find them).
The html part looks as follows:
<select class="form-control attributoSelect2" name="attributiSelezionati" id="attributoSelect2" value="#Model.AttributiSelezionati"></select>
There are no < option > items inside < select > because the ajax call takes care of populating the list, like this:
$('.attributoSelect2').select2({
placeholder: "Cerca Attributo",
multiple: true,
allowClear: true,
minimumInputLength: 0,
ajax: {
dataType: 'json',
delay: 150,
url: "#Url.Action(MVC.Configurazione.Attributi.CercaAttributi())",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: item.Id,
text: item.Descrizione,
children: item.Children.map(function (itemC) {
return {
id: itemC.Id,
groupid: itemC.GroupId,
text: itemC.Descrizione,
};
})
};
})
};
}
}
});
Finally my javascript looks as follows:
$('.attributoSelect2').on("select2:selecting", function (evt, f, g) {
disableSel2Group(evt, this, true);
});
$('.attributoSelect2').on("select2:unselecting", function (evt) {
disableSel2Group(evt, this, false);
});
function disableSel2Group(evt, target, disabled) {
var selId = evt.params.args.data.id;
var group = evt.params.args.data.groupid;
var aaList = $(".attributoSelect2 option");
$.each(aaList, function (idx, item) {
var data = $(item).data("data");
var itemGroupId = data.groupid;
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}
The problem is that this line:
var aaList = $(".attributoSelect2 option");
does not load all the option elements because they are not loaded yet. They would be loaded later on using the ajax call. Does anyone have an idea of how to resolve this problem?
In Datatable's Select plugin, there is a way to programmatically select a row:
https://datatables.net/reference/api/row().select()
But this will also trigger the row's select event, which is not ideal in my context as it will get into an infinite loop...
Is there a way of doing this without having to use some control variable?
The bit in their API for the select function is as follows :
apiRegisterPlural( 'rows().select()', 'row().select()', function ( select ) {
var api = this;
if ( select === false ) {
return this.deselect();
}
this.iterator( 'row', function ( ctx, idx ) {
clear( ctx );
ctx.aoData[ idx ]._select_selected = true;
$( ctx.aoData[ idx ].nTr ).addClass( ctx._select.className );
} );
this.iterator( 'table', function ( ctx, i ) {
eventTrigger( api, 'select', [ 'row', api[i] ], true );
} );
return this;
} );
It seems I just need to figure out the ctx.aoData[ idx ]._select_selected = true; part, is ctx the row object? I'm clueless.
I know this question is very old, but for those coming here later on might like an answer.
Datatables has a select event and a user-select event.
Just use the user-select event where applicable and leave the select event for all other purposes.
https://datatables.net/reference/event/user-select
For example,
var table = $('#example').DataTable( {
select: true
} );
table
.on( 'user-select', function ( e, dt, type, cell, originalEvent ) {
if ( originalEvent.target.nodeName.toLowerCase() === 'img' ) {
e.preventDefault();
}
} );
Update : Just to add an additional choice since the user-select event does fire even on a deselect. One way to avoid some issues I think many people have is when the table is initialized they programmatically select items. You can avoid this trigger by simply enabling your select and deselect events only after the table has been initialized.
Datatables has an initComplete event. So do it like so. Where table is a variable to your datatable reference.
initComplete: function(settings, json) {
table.on('select', function( e, dt, type, indexes ) {
});
}
Ive been trying to get data from a table to a modal in ReactJS, trying as in trying to get it to work with minimal effort. I think I understand how Components work ok. But when displaying data in the modal I want the component to first go through the list and remove 'selected' class on the rest of the rows and then display the selected row. Right now my modal only displays the last row, regardless of where I click.
var BoatRow = React.createClass({displayName: 'BoatRow',
handleClick: function(event){
this.setState({className:'selected'});
},
getInitialState: function(){
return (
{
className:'!selected',
}
)
},
render:function(){
var listed = this.state.className ? 'selected' :
localStorage.setItem('boat', JSON.stringify({
name:this.props.boat.Name,
//some data
}));
return (
React.DOM.tr({className:this.state.className},
React.DOM.td(null, this.props.boat.Name),
//rest of table row data
React.DOM.button({type: "button", 'data-toggle': "modal", 'data-target': "#modalContent", onClick:this.handleClick
}, "Select" )
)
)
)
}
});
Im first going through the JSON object and pushing it to an array.
var AllBoatList = React.createClass({displayName: 'AllBoatList',
render: function(){
var rows = [];
var lastAvailable = null;
this.props.boats.forEach(function(boat, i){
if(boat.Availability !== 0){
rows.push(BoatRow({boat:boat, key:boat.id}));
}
});
return(
React.DOM.table({id:"boat-table"},
//table head
)
),
React.DOM.tbody(null, rows)
)
);
}
});
var data = [{
"Name": "Boat Name",
"id": "1"
}, //rest of Json data
}
]
React.render(AllBoatList({boats:data}),
document.getElementById('all-boats')
);
And this is where the modal data gets displayed.
var Boats = require(['./assets/src/scripts/boats']);
var BoatModal = React.createClass({displayName: 'BoatModal',
getInitialState: function(){
return {
value: JSON.parse(localStorage.getItem('boat'))
}
console.log(this.state.value);
},
render:function(){
return (
React.DOM.div({className: "DisplayContainer"},
React.DOM.p(null,
this.state.value
)
)
)
}
});
React.render(BoatModal({}), document.getElementById('modal-body')
);
The components work fine displaying the table and selecting the correct row, changing classes. Im only having problems where the data displayed on the modal is not my selection, but always the last row. How can I fix this?
I've got it working finally. I dont know if I fully understand this yet, but I had to move all onClick events to the event handler. Modal works with correct data, with this change
var BoatRow = React.createClass({displayName: 'BoatRow',
handleClick: function(event){
this.setState({className:'selected'});
//this is where storage should happen
localStorage.setItem('boat', JSON.stringify({
"Name":this.props.boat.Name
//adding this line fixed it
})).bind(this.props.boat.Name);
console.log("storage written");
},
getInitialState: function(){
return (
{
className:'!selected'
}
)
},
render:function(){
var listed = this.state.className ? '!selected' : 'selected'
...
I use a jqGrid with jquery autocomplete on one column.
{
name : 'mdmKndcode',
index : 'mdmKndcode',
width : 150,
align : "center",
editable : true,
edittype: 'text',
editoptions: {
dataInit: function(elem) {
var cache = {};
$(elem).autocomplete({
source: function( request, response ) {
var term = request.term;
console.log(term);
if(term in cache){
response(cache[term]);
return
}
$.getJSON( "/example/json/"+term, request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
},
minLength:3
});
}
}
In the grid I can see the results of json request in autocomplete list. This works fine. But I am not able to select a value in this list. The autocomplete list getting closed and lose the focus of the column after a mouseover or Keyboard press on the list.
Tried also with "select" function but same result.
Want to have the selection of the values in the list like in this Demo
Looking at your jsfiddle, the problem is that you are including jqueryui twice jquery-ui.js and jquery-ui-custom.min.js , most likely both of them have autocomplete and that causes troubles.
Remove one of them and that will fix the issue.
See here
Here's my DataGrid:
// $ is a reference to `this` as it lies in an anonymous function
$.grid = new DataGrid({
store : $.dataStore,
query : {id : "*"},
structure : [
{
noscroll : true,
cells : [{ name : "Recipe", field : 'name', width : '200px' }],
},
{
cells : [
[
{ name : 'ID#', field : 'id', width : '50px'},
{ name : 'Category', field : 'category', width : '100px'},
{ name : 'Status', field : 'status', width : '100px'},
{ name: "Actions", width : '200px', type: dojox.grid.cells._Widget, formatter : $._actionButtons}
]
] // end cells
}
]
}, $.targetNode)
$.grid.startup();
$.grid.on("RowClick", function(e){
console.log(this.getItem(e.rowIndex))
})
And my formatter object for the Actions cell:
_actionButtons : function(){
var _self = this;
var _args = arguments;
this.group = new Pane()
var full = new Button({
label: 'View Full',
style : { fontSize : '80%'},
onClick : function(){
try {
_self.grid.onRowClick.apply(this, arguments)
}catch(e){}
}
});
full._destroyOnRemove = true;
var edit = new Button({
label : 'Edit',
style : {fontSize: '80%'}
});
edit._destroyOnRemove = true;
construct.place(full.domNode, this.group.containerNode)
construct.place(edit.domNode, this.group.containerNode)
return this.group;
}
I'm trying to get access to the event object that would be passed by a normal onRowClick event on the DataGrid. As it sits now this kinda works, but on the on("RowClick"...) block I get multiple logs. Without the try...catch block I get an error as the rowIndex doesn't exist in e, then 2 more logs where it does exist.
This is the 4th or so idea I've had included pub/sub, emit(), etc. I have a feeling that the multiple logs are caused by the bubbling behavior (Button -> Row -> DataGrid or somesuch), but getting the onRowClick's event object to get passed into the Buttons created in the formatter seems impossible.
I just want to access the rowIndex (and other DataGrid-esque properties) from the Button widget's onClick event to process according to the button pressed.
Along the same lines, but here's what I came up with that seems to be working in a direction where what I'm envisioning will happen. Adjusted cell where the buttons will be:
{ name: "Actions", width : '200px', type: dojox.grid.cells._Widget, formatter :
function(){
return $._actionButtons.call($, arguments);
}
}
Adjusted onClick function in the returned Button widget:
_actionButtons : function(){
var _index = arguments[0][1],
_item = this.grid.getItem(_index)
_self = this;
// some code removed
onClick : function(){
console.log(_self.dataStore.getValue(_item, 'name'), "clicked")
}
}
I'll probably end up extending Button to handle this a bit better, but for now, voila!
Sometimes it just helps to write it down and put it out there for your brain to panic and figure out the solution before anyone else does :)
Minor update...
There is the formatterScope parameter for the DataGrid, but it applies to all formatter's and would therefore mess up anything requiring cell scope and not DataGrid scope. The above method allows me to access everything I need.