Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent member controller from child controller

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.

like image 775
Marcos Avatar asked Oct 30 '14 12:10

Marcos


People also ask

How do you access child controller scope in parent controller?

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.

Which event should be used for passing data from child controller to parent controller?

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).

What is parent and child controller Angularjs?

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.


1 Answers

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.

like image 119
James_D Avatar answered Jan 04 '23 03:01

James_D