Gigin
Gigin

Reputation: 21

Ember.js setup controller and then accesing model within the controller

I'm new to Ember.js, this is my first app which has a notifications area, always visible. As this notification area is included in the application template and there is no specific route for it, I added the number using the {{render}} Helper and setting the model from the ApplicationRoute:

<script type="text/x-handlebars">
    ...
    {{#link-to "notifications"}}
        {{ render "notification-totals" }}
    {{/link-to}}

    <div class="dropdown">
       {{outlet notifications}}
    </div>
    ...

</script>

<script type="text/x-handlebars" data-template-name="notification-totals">
    {{this.firstObject.total}}
</script>

The ApplicationRoute sets the model to the controller:

App.ApplicationRoute = Ember.Route.extend({
    setupController: function() {
        this.controllerFor('notification-totals').set('model',this.store.find('notification.total'));
    }
});

The Model:

App.NotificationTotal = DS.Model.extend({
    total: DS.attr('number')
});

How can I access the model within the Controller? Nothing I try seems to work, for example:

App.NotificationTotalsController = Ember.ObjectController.extend({
    total: function() {
       var model = this.get('model');
       .....
    }.property()
});

Upvotes: 0

Views: 1869

Answers (1)

panta82
panta82

Reputation: 2721

Your code should work fine. You should be getting an array of your model objects, because that's what the route is setting as model.

For example:

  <script type="text/x-handlebars">
    <div><h3>Notifications:</h3>
    {{ render "notification-totals" }}</div>
  </script>

  <script type="text/x-handlebars" data-template-name="notification-totals">
    {{total}}
  </script>
App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.ApplicationRoute = Ember.Route.extend({
    setupController: function() {
      var data = [
        {
          total: 7
        }, {
          total: 8
        }, {
          total: 12
        }
      ];
      this.controllerFor('notification-totals').set('model', data);
    }
});

App.NotificationTotalsController = Ember.ObjectController.extend({
    total: function() {
      var model = this.get('model');
      return model
        .mapBy("total")
        .reduce(function (prev, cur) {
          return prev + cur;
        }, 0);
      console.log(model);
    }.property("[email protected]")
});

This controller will access all the model objects and generate the sum ({{this.firstObject.total}} will get you totals only from the first object). Working demo here.

If you're still getting nothing, check if your data source is getting anything (this demo uses hardcoded values instead of ember data).

Upvotes: 2

Related Questions