This question is similar to this, but I need to access parent member (not control). I don't know if is possible to do without using Dependency Injection.
For example, I have a Parent with have a member calls User, I need to access from child controller to User.
In angular there is a scope variable called $parent (i.e. $scope. $parent). $parent is used to access parent scope from child controller in Angular JS.
Using $broadcast and $emit $broadcast always use to pass data from Parent Controller to child controller (Down direction) and $emit service use to pass data. From child controller to parent controller (Up direction).
Angular scopes include a variable called $parent (i.e. $scope. $parent ) that refer to the parent scope of a controller. If a controller is at the root of the application, the parent would be the root scope ( $rootScope ). Child controllers can therefore modify the parent scope since they access to it.
Just pass the reference from the parent controller to the child controller in the parent controller's initialize()
method:
ParentController.java:
public class ParentController {
@FXML
private ChildController childController ;
private User user ;
public void initialize() {
user = ...;
childController.setUser(user);
}
}
ChildController.java:
public class ChildController {
private User user ;
public void setUser(User user) {
this.user = user ;
}
}
You can also do this with JavaFX Properties instead of plain objects, if you want binding etc:
ParentController.java:
public class ParentController {
@FXML
private ChildController childController ;
private final ObjectProperty<User> user = new SimpleObjectProperty<>(...) ;
public void initialize() {
user.set(...);
childController.userProperty().bind(user);
}
}
ChildController.java:
public class ChildController {
private ObjectProperty<User> user = new SimpleObjectProperty<>();
public ObjectProperty<User> userProperty() {
return user ;
}
}
As usual, the parent fxml file needs to set the fx:id
on the fx:include
tag so that the loaded controller is injected to the
<fx:include source="/path/to/child/fxml" fx:id="child" />
the rule being that with fx:id="x"
, the controller from the child fxml will be injected into a parent controller field with name xController
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With