I have three tiers of objects, each as one to many. I'd like, when a different notebook is selected, that the page and column view elements get cascading updates.
Notebook > Pages > Columns
With notebooksController and notebookController I can bind
App.Notebook = SC.Record.extend({
name: SC.Record.attr(String),
pages: SC.Record.toMany('App.Page', {isMaster: YES, inverse: 'notebook'})
});
App.Page = SC.Record.extend({
pageNumber: SC.Record.attr(Number),
notebook: SC.Record.toOne('App.Notebook', {isMaster: NO, inverse: 'pages'}),
columns: SC.Record.toMany('App.Column', {isMaster: YES, inverse: 'page'})
});
App.Column = SC.Record.extend({
columnNumber: SC.Record.attr(Number),
page: SC.record.toOne('App.Page', {isMaster: NO, inverse: 'columns'})
});
Following this, I can't seem to get the content binding for pagesController to work. I want the contents of pagesController, pageController, columnsController, and columnController to be cascaded down so that when a user clicks a different notebook, the views presented automatically flick across to the correct content.
ArrayController notebooksController
// contents filled from fixture
ObjectController notebookController
// bound to notebooksController selection
ArrayController pagesController
// contentBinding: 'notebookController.pages' does not work!
ObjectController pageController
// bound to pagesController selection
// and down to column
Assuming you have a single Notebook, try
App.notebookController = SC.ObjectController.create({
// call App.notebookController.set('content', aNotebook)
// to set the content on this controller
});
App.pageController = SC.ArrayController.create({
// the notebookController is a proxy to the its content, so you dont need
// 'content' in the binding contentBinding: 'App.notebookController.pages'
// bind the list view to App.pagesController.arrangedObjects. If you look in the code
// arranged objects is a reference to the array controller itself, which has array methods
// on it
});
App.pageSelectionController = SC.ObjectController.create({
// You need to add
//
// selectionBinding: 'App.pageSelectionController.content
//
// to the collection view where you select the page
// you can do this in places to see when things change. This controller is just a proxy
// to the selected page.
selectionDidChange: function(){
console.log('page selection changed to [%#]'.fmt(this.get('content');
}.observes('content')
});
App.columnsController = SC.ArrayController.create({
contentBinding: 'App.pageSelectionController.columns'
// again, where you want to show the columns, bind to
// App.columnsController.arrangedObjects
});
I found the answer.
Turns out you can indeed simply use App.notebookController.pages.
The problem was, my fixtures were not set up correctly. It is not enough to map the child to the parent, the parent has to be mapped back to the child.
I originally had:
Autofocus.Notebook.FIXTURES = [
{ guid: 1, title: "Home Notebook", columnCount: 2},
{ guid: 2, title: "Work Notebook", columnCount: 2}
];
And was all fixed when I did the following:
Autofocus.Notebook.FIXTURES = [
{ guid: 1, title: "Home Notebook", columnCount: 2, pages: [11, 12] },
{ guid: 2, title: "Work Notebook", columnCount: 2, pages: [21, 22]}
];
Related
Using mat-select in multiple mode, is it possible to pre-set the selected values if the values that are part of the select options are objects?
For example if the options in the select are as follows
toppingList: any[] = [
{ id: 1, description: 'Extra cheese' },
{ id: 2, description: 'Mushroom' },
{ id: 3, description: 'Onion' },
{ id: 4, description: 'Pepperoni' },
{ id: 5, description: 'Sausage' },
{ id: 6, description: 'Tomato' }
];
Then can you pre-set the selected values for that mat-select as such?
this.toppings.setValue([{ id: 1, description: 'Extra Cheese' }]);
Taking this stackblitz as an example you see that the the form values are getting set as desired, but the select buttons in the drop down itself are not showing as checked.
Is this even possible, or am I doing something wrong?
as i know for equality of two object, for example in java, you need write equal / hashcode for detect what object equal to another one.
you bind select value to object and typescript could not understand what compare object together. so i change your sample and bind value of options to id and it works!
see this stackblits
The Angular Material documentation gives a nice example for how to add selection to a table (Table Selection docs). They even provide a Stackblitz to try it out.
I found in the code for the SelectionModel constructor that the first argument is whether there can be multiple selections made (true) or not (false). The second argument is an array of initially selected values.
In the demo, they don't have any initially selected values, so the second argument in their constructor (line 36) is an empty array ([]).
I want to change it so that there is an initially selected value, so I changed line 36 to:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
This changes the checkbox in the header to an indeterminate state (as expected), but does not cause the row in the table to be selected. Am I setting the initial value incorrectly, or what am I missing here? How can I set an initially selected value?
Tricky one. You need to initialize the selection by extracting that particular PeriodicElement object from your dataSource input, and passing it to the constructor.
In this particular case, you could code
selection = new SelectionModel<PeriodicElement>(true, [this.dataSource.data[1]);
It's because of the way SelectionModel checks for active selections.
In your table markup you have
<mat-checkbox ... [checked]="selection.isSelected(row)"></mat-checkbox>
You expect this binding to mark the corresponding row as checked. But the method isSelected(row) won't recognize the object passed in here as being selected, because this is not the object your selection received in its constructor.
"row" points to an object from the actual MatTableDataSource input:
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
But the selection initialization:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
happens with a new object you create on the fly. Your selection remembers THIS object as a selected one.
When angular evaluates the bindings in the markup, SelectionModel internally checks for object identity. It's going to look for the object that "row" points to in the internal set of selected objects.
Compare to lines 99-101 and 16 from the SelectionModel source code:
isSelected(value: T): boolean {
return this._selection.has(value);
}
and
private _selection = new Set<T>();
I was facing the same issue, I used dataSource to set the initial value manually in ngOnInit()
ngOnInit() {
this.dataSource.data.forEach(row => {
if (row.symbol == "H") this.selection.select(row);
});
}
If you do the following, it works too
selection = new SelectionModel<PeriodicElement>(true, [ELEMENT_DATA[1]])
To select all you can do
selection = new SelectionModel<PeriodicElement>(true, [...ELEMENT_DATA])
I hope the answer is helpful
Or more dynamically if you have a set of values and you want to filter them before:
selection = new SelectionModel<PeriodicElement>(true, [
...this.dataSource.data.filter(row => row.weight >= 4.0026)
]);
This gets more tricky if you have data loading asynchronously from an api. Here is how I did it:
Firstly I have implemented the DataSource from "#angular/cdk/table". I also have an RxJS Subject that fires whenever data is loaded (first time or when user changes page in the pagination section)
export abstract class BaseTableDataSource<T> implements DataSource<T>{
private dataSubject = new BehaviorSubject<T[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
private totalRecordsSubject = new BehaviorSubject<number>(null);
public loading$ = this.loadingSubject.asObservable();
public dataLoaded$ = this.dataSubject.asObservable();
public totalRecords$ = this.totalRecordsSubject.asObservable().pipe(filter(v => v != null));
constructor(){}
connect(collectionViewer: CollectionViewer): Observable<T[]>{
return this.dataSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.dataSubject.complete();
this.loadingSubject.complete();
this.totalRecordsSubject.complete();
}
abstract fetchData(pageIndex, pageSize, ...params:any[]) : Observable<TableData<T>>;
abstract columnMetadata(): {[colName: string]: ColMetadataDescriptor };
loadData(pageIndex, pageSize, params?:any[]): void{
this.loadingSubject.next(true);
this.fetchData(pageIndex, pageSize, params).pipe(
finalize(() => this.loadingSubject.next(false))
)
.subscribe(data => {
this.totalRecordsSubject.next(data.totalNumberOfRecords);
this.dataSubject.next(data.records)
});
}
}
Now when I want to pre-select a row, I can write a function like this in my component which hosts a table that uses an implementation of the above mentioned data source
selectRow(rowSelectionFn: (key: string) => boolean){
this.dataSource.dataLoaded$.pipe(takeUntil(this.destroyed$))
.subscribe(data => {
const foundRecord = data.filter(rec => rowSelectionFn(rec));
if(foundRecord && foundRecord.length >= 0){
this.selection.toggle(foundRecord[0]);
}
});
}
I'm using Knockout 3 with the plugin jqAutocomplete by Ryan Niemeyer. I have a problem with this model:
var ViewModel = function() {
var self = this;
self.myOptionsObs = ko.observableArray([
{ id: ko.observable(1), name: ko.observable("item 1 o"), description: ko.observable("item label 1 o") },
{ id: ko.observable(2), name: ko.observable("item 2 o"), description: ko.observable("item label 2 o") },
{ id: ko.observable(3), name: ko.observable("item 3 o"), description: ko.observable("item label 3 o") }
]);
self.myValueObs = ko.observable();
};
ko.applyBindings(new ViewModel());
<input data-bind="jqAuto: { source: myOptionsObs, value: myValueObs, inputProp: 'name', template: 'itemTmpl' }" />
As you can see, there is an observable array and each element is also an observable.
The autocomplete don't work well. As you can see in this Fiddle, the left column has an observable array but its elements aren't observable. If you click in the left box and write something, a list of options appear.
But in the right column, you have the same, but the element's are all observable. If you click in the right box and write something, when the list appear, if you move the cursor up and down, you could see that the row 'name' gets deleted and filled with zeros.
What I have to change in my data-bind attribute?
This question is related with this question.
I have to say that this solution works ok for me. But the updated plugin don't.
Thanks !!
The jqAutoComplete plugin isn't setup to work with observable properties (although it could be enhanced to do so without much work).
For now, I think that your best bet is to create a computed that will always return a plain and up-to-date version of your options.
self.myOptionsObs.plain = ko.computed(function() {
return ko.toJS(self.myOptionsObs);
});
Sample: http://jsfiddle.net/rniemeyer/45cepL9b/
I'll try to take a look at some point about supporting observable properties. Shouldn't take many changes.
I have this json model:
model/data.json
{
"orders" : [
{
"header" : { "id" : "00001", "description" : "This is the first order" },
"items" : [
{ "name" : "Red Book","id" : "XXYYZZ" },
{ "name" : "Yellow Book", "id" : "AACCXX" },
{ "name" : "Black Book", "id" : "UUEEAA" },
]
},
{
// another order with header + items
},
.....
]
}
and I'm assigning it onInit to the view, like this:
var model = new sap.ui.model.json.JSONModel("model/data.json");
sap.ui.getCore().setModel(reqModel);
I'm trying to display a list of orders in the first view (showing the id), like this:
var list = new sap.m.List({
id: "mainList",
items: []
});
var items = new sap.m.ActionListItem({
text : "{id}",
press : [ //click handler, onclick load the order details page ]
});
list.bindItems("/orders", items);
.... // add list to the page etc etc
What I cannot do, is connect each order to its header->id.. I tried
text: "/header/{id}"
text: "{/header/id}"
in the items declaration, and
list.bindItems("/orders/header", items)
in the list binding, but none of them works.. The id value is not displayed, even though a "blank" list item is shown..
Any idea? What am I doing wrong?
Thank you
The solution was one of those I tried (but I don't know why it didn't work at that time)
text: "{/header/id}"
The ListItem acts as a Template for a list/array of objects. That's why you bind it against an array structure in your data:
list.bindItems("/orders", itemTemplate)
That makes bindings of the ListItem relative to /orders and therefore your item should look like this without leading '/' (absolute paths would look like this /orders/0/header/id asf.):
var itemTemplate = new sap.m.ActionListItem({
text : "{header/id}",
press : [ //click handler, onclick load the order details page ]
});
Not quite sure how you made it work the way you have shown... May be it's not as picky as I thought.
Btw: For whatever reason the ResourceModel builds an exception of that syntax. You can always omit the leading '/' when dealing with ResourceModels (probably because they do not allow nested structures).
BR
Chris
Cannot add comments yet, therefore an answer to you solved Problem, that could answer the initial problem. (And inform People using that example in any way)
In the current code listing you use the variable "reqModel" to set the model, but the variable with the model in it is named "model" in the line before. Maybe that was the first reason why both of your examles would not work?
Perhaps this error was cleared on rewriting some passages while testing.
greetings! -nx
This question already has an answer here:
OData Model Not Working
(1 answer)
Closed 20 days ago.
I have created a webservice and trying to bind data using oData protocol in SAPUI5.
I have created a table:
createContent : function(oController) {
jQuery.sap.require("sap.ui.table.Table");
//Create table control with properties
var oTable = new sap.ui.table.Table({
width : "100%",
rowHeight : 50,
title : "Lst of Items",
selectionMode : sap.ui.table.SelectionMode.None
});
oTable.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "PO Number"
}),
template : new sap.ui.commons.TextView({
text : "{PoNumber}"
}),
}
));
oTable.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "Item"
}),
template : new sap.ui.commons.TextView({
text : "{PoItem}"
}),
}
));
//Filter values for a certain PO
var aFilter = [];
aFilter.push( new sap.ui.model.Filter("PoNumber", sap.ui.model.FilterOperator.EQ, "4500000043") );
oTable.bindRows({
path: "/PurchaseOrderItemCollection",
filters: aFilter
});
return oTable;
}
The output should be as follows:
PONumber POItem
4500000043 0010
4500000043 0020
But what I get is:
PONumber POItem
4500000043 0020
4500000043 0020
So it shows the last item twice and doesn't show the first item. If I put a break point in my web service code then it is populated correctly.
The data model is created in the following way:
var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, false, "user", "passw");
sap.ui.getCore().setModel(oModel);
I have encountered this. Problem is with your data model. Ensure that for the entity both PO number and PO item are marked as keys. Refresh any metadata cache, ensure that both properties appear as keys and try again. It should work.
Thanks
Krishna
My understanding is every entity/entry in the collection should have a unique id <entry><id>...</id></entry>.
And in my case, the returned collection had no ids set for the entities. So the bound ui element finds multiple objects with same id (in this case empty id) and ends up displaying value which it finds the last.
The same should apply even if the id is same across all entities.
Hope it helps, if you have not already found what the problem is.
Thanks,