Assigning the Model to the UI
You must assign a model instance to the UI before you can bind controls to it.
For this purpose, you can use the
setModel method, which is available on every control. The first parameter passed to this method is the model to be set. The second (optional) parameter can be used to define a name for the model. If the name is omitted, this will set the so-called default model without a name.
In the figure, Setting the Model for the View, the instantiated JSON model is assigned to the view via the
setModel method. As model name,
customer is used.
The name of the model will be specified later during data binding (see below).
Naming models makes it possible to not only use one model for an application, but to define different areas in an application with different models. You can even assign models to individual controls. You can also define nested models, for example, a JSON model for the application and an OData model for a table control contained in the application.
When you specify a model for a section or control, it is propagated to all aggregated child controls. So, if you set a model for a container control, all controls contained (aggregated) in that container will have access to that model.
In the shown example, all controls placed on the view can access the model.
However, models can also be defined declaratively via the
manifest.json application descriptor. They are then automatically created and destroyed along the life-cycle of the component.
To define a model declaratively for a component, an entry is added to the
models property from the
sap.ui5 namespace. The key of this entry represents the model name, where an empty string ("") stands for the default model. The
type property of the entry is used to set the name of the model class and the
uri property can be used to specify the relative path to the model data within the component.
The figure, Declarative Approach, shows an example that instantiates a JSON model that loads its data from the
data.json file. This file is located in the
model folder of the project. The instantiated model is set as the default model (without a name) for the component and is thus available in all views of the component.