Passing data to view

How to pass data from a controller's action to the a view?

If you have already experienced MVC frameworks, then you are certainly used to pass data to views before rendering them. This topic is about how to keep doing that.

Passing the data

It is as easy as follows:

    
    @ApplicationScoped 
    public class Hello extends Controller {
        public void world() throws MvcException{
    
            Map<String,Object> data = new HashMap<>();
            data.put("name","John doe");
            data.put("age",44);
            data.put("email","john.does@emerjoin.org");
            
            this.callView(data);//Pass the data to the view
    
        }
    
    }
    

NOTE
Each key from the data HashMap becomes a variable in your view's scope .

Using the data

The data passed from the controller is immediately added to the $scope of the view, meaning that, such data is accessible from both: presentation and view controller.

From HTML

We are simply going to render the data passed from the controller:

    <div>
        <span>{{name}}</span>
        <span>{{age}}</span>
        <span>{{email}}</span>
    </div>

Easy right? You can do a lot more with that data. Take a look at the AngularJS expressions docs.

From the View controller

Let's now print the data on the browser's console, from the view's controller:

    Hi.view(function($scope){
               
        //Calling this function will print the data      
        $scope.myFunction = function(){
        
            console.log($scope.name);
            console.log($scope.age);
            console.log($scope.email);
        };
    
    });     

TIP ABOUT CONTROLLERS
Avoid contacting databases on controllers and then passing data to views because it degrades the user experience and complicates your data flow.
Use Frontiers to fetch data to the views. This way you can provide a better user experience and after all, Hi-Framework is only funny if you do things in the ajax way.

Github Repository