Search code examples
ember.jsember-controllers

Ember component cannot use access controller property via "needs"


I'm trying to change a controller's property from a component as follows(JSBIN example http://jsbin.com/gevuhu):

App.CategoryManagerController = Ember.Controller.extend({
  selectedCategory: null,
});

App.BlogPostComponent = Ember.Component.extend({
    needs: ['categoryManager'],
    selectedCategory: Ember.computed.alias('controllers.categoryManager.selectedCategory'),
    actions:{
        selectedCategory: function (){
            this.set('selectedCategory',1);
        }
    }
});

but getting the error Property set failed: object in path "controllers.categoryManager" could not be found or was destroyed.

Is it that we cannot use "needs" in components ?


Solution

  • Ember Components are completely isolated from surrounding context including controllers (see here). That's the bad news. The good news is that if you pass selectedCategory into the component, it will become 2-way bound, so any change to it in the component will be known by your controller.

    So, your controller could be something like:

    App.ApplicationController = Ember.ObjectController.extend({
        needs: ['categoryManager'],
        selectedCategory: Ember.computed.alias('controllers.categoryManager.selectedCategory'), 
        selectedCategoryChanged: function(){
          alert("NEW CATEGORY: " + this.get('selectedCategory'));
        }.observes('selectedCategory')
    });
    

    and then in your application template, you can say

    {{ blog-post selectedCategory=selectedCategory }}
    

    See a working example here