ember.jsember-modelember-controllers

Accessing a model collection in controller - Ember2.5


When trying to access the model of a controller when creating a computed property on the controller, I get the following error:

model.uniqBy is not a function

app/controller/ticket.js

export default Ember.Controller.extend({
  statuses: Ember.computed('model', function() {
      var model = this.get('model');
      return model
              .uniqBy('status')
              .map(function(i) { return i.status; })
              .toArray();
  }),
});

The model I'm giving to the controller is a collection returned from this.store.findAll('ticket');, but trying to iterate through it seems to be causing the above error. Is the collection given to the model not supposed to be an Ember.Enumerable object? Should I be trying to access the collection via the DS.Store (in which case I don't understand the need to pass a model to the controller)?


Solution

  • Ember.computed.uniqBy

    A computed property which returns a new array with all the unique elements from an array, with uniqueness determined by specific key

    Please try this instead for your computed property

    statuses: Ember.computed.uniqBy('model', 'status')
    

    EDIT

    You can use ember computed map on this property to fine tune your array if needed, for example like this

    status: Ember.computed.map('statuses', function(status, index)
      return status.toUpperCase() + '!';
    })
    

    Another way is that computed property uses dynamic aggregate syntax as described here

    https://guides.emberjs.com/v2.6.0/object-model/computed-properties-and-aggregate-data/

    so Ember.computed('model.@each.status', function()

    Hope it helps