I am working on a Word add-in, using the Office JS API, trying to add a Content Control around a Table Binding in the document.
The issue I am experiencing is after the Binding around the table is selected, using goToByIdAsync()
, the Content Control is created around the last row of the table only, not the selection. Returning the value of ctx.document.getSelection()
I can see the selected Range is only the last row in the Selected Table. I need to use the Binding object to know the selected cell ranges of Table. Is there something I am doing wrong?
var bindingId = '123';
var doc = Office.context.document;
// Create table in document.
doc.setSelectedDataAsync(tableValue, { coercionType: Office.CoercionType.Table }, function (asyncResult) {
// Add Binding to table
doc.bindings.addFromSelectionAsync(Office.BindingType.Table, { id: bindingId }, function (asyncResult) {
// Select the table object
doc.goToByIdAsync(bindingId, Office.GoToType.Binding, { selectionMode: 'selected' }, function (asyncResult) {
// Create Content Control
createCC();
});
});
});
function createCC(){
Word.run(function (ctx) {
var range = ctx.document.getSelection();
var html = range.getHtml();
return ctx.sync().then(function () {
console.log('Selected Range', html.value); // Only displays last row in the table.
var myContentControl = range.insertContentControl();
myContentControl.tag = bindingId;
myContentControl.title = 'My Content Control';
return ctx.sync().then(function () {
//Content control for table created
});
}).catch(function (err) {
errorHandler(err);
});
});
}
This is a great question! thanks for asking. I will suggest you to change a bit the approach on how to achieve the scenario you want. First of all goToById should not be used to get the range of any object, this is just for navigation purposes. It will be way more deterministic if you can insert a table, wrap it with a named content control (assigning a title to it), create a binding (using addFromNamedItem and not using addFromSelection as you don't have a solid selection :) ) , and then just subscribe to the bindingSelectionChanged event and do whatever you need to do with the table or selected cells.
The following code shows just that. Hopefully it will set you up in the right direction. I added a bunch of comments of each of the steps I described above.
thanks and happy coding!