Krizsán Balazs
Krizsán Balazs

Reputation: 385

EmberJS passing variable to the layout

I have a really basic test app. It has 2 pages an empty index and a login form on an other page. And I would like to know how can I pass variables to the layout which is the same on every page (user name/status for display it and display login/logout by status).

Or the best solution could be something like this: pass a user model to the AppController which is available from anywhere (like login page or login modals) and If I change and save the data the site template is just changing by the passed variables.

I was trying to find a good way, I find a few ones but none of them was working :( If you know a working way please share me or show me what is the solution.

Here is my code: the JS I have:

App = Ember.Application.create();

App.ApplicationController = Ember.Controller.extend({});


/* *** Index *** */
App.IndexView = Ember.View.extend({
    layoutName: 'app_view'
});

App.IndexController = Ember.Controller.extend({
});


/* *** LOGIN *** */
App.Router.map(function () {
    this.resource("login");
});
App.LoginView = Ember.View.extend({
    layoutName: 'app_view'
});
App.LoginController = Ember.Controller.extend({
    login: function() {
        // blah blah
    }
});

Layout template:

<script type="text/x-handlebars" data-template-name="app_view">
    <header id="site">
        {{#link-to "index"}}Index{{/link-to}}
        {{#link-to "login"}}Login{{/link-to}}
        {{variablaWhatIWant}}
    </header>
    <hr />
    <section id="content">
        {{yield}}
    </section>
    <hr />
    <footer id="main">
        Footer
    </footer>
</script>

2 view templates:

<script type="text/x-handlebars" data-template-name="index">
    Hello INDEX page!
</script>
<script type="text/x-handlebars" data-template-name="login">
    <form class="form-horizontal" {{action "login" on="submit"}}>
        <div class="control-group">
            Username: {{input value=username type="text"}}
        </div>
        <div class="control-group">
            Password {{input value=password type="password"}}
        </div>
        <button type="submit" class="btn">Log in!</button>
    </form>
</script>

Thank you very much! :)

Upvotes: 1

Views: 470

Answers (1)

Jakeii
Jakeii

Reputation: 1273

You have the right idea, see managing dependancies between controllers http://emberjs.com/guides/controllers/dependencies-between-controllers

just set the needs property, and you can access that controller from any other

App.LoginController = Ember.Controller.extend({
    needs: ['application'],
    login: function() {
        this.authenticate(this.get('username'), this.get('password')).then(function(user) {
             this.set('controllers.application.user', user);
        },
        function(err) {
             //auth err
        }
    }
});

Upvotes: 1

Related Questions