8

I am using Ember's Need Api to call a method of a controller in another controller. I am able to get the instance of the controller but when I am calling it method it returns me this error TypeError: Object [object Object] has no method.

This is how I am calling it:

Cards.CardsIndexController = Ember.Controller.extend({
    needs: 'account_info',
     actions: {
        accountInfoStart:function(){
               console.log(this.get('controllers.account_info').test()); // error here


        }
    }
});

This is the controller whose function I want to call

Cards.AccountInfoController = Ember.Controller.extend({


    actions:{

        test: function(){

            alert(1);
        }

    }

});

How can I solve it?

llrs
  • 3,308
  • 35
  • 68
mohsinali1317
  • 4,255
  • 9
  • 46
  • 85

3 Answers3

12

test is not technically a method, but an action or event. Use the send method instead:

this.get('controllers.account_info').send('test', arg1, arg2);
GJK
  • 37,023
  • 8
  • 55
  • 74
  • For people who need it to work with nested folders, here's a solution for it: http://stackoverflow.com/a/29269015/499700 – poweratom Mar 26 '15 at 00:29
5

As per Ember documentation; create a property that lazily looks up another controller in the container. This can only be used when defining another controller.

legacy ember application example:

App.PostController = Ember.Controller.extend({
  accountInfo: Ember.inject.controller()

  this.get('accountInfo').send('test')
});

modern ember application example:

// in an ember app created with ember-cli
// below snippet would be the app/controllers/post.js file
import Ember from 'ember';
export default Ember.Controller.extend({
  appController: Ember.inject.controller('application')
});

You can find more documentation about Ember.inject here

  • 2
    For users cruising the web, this answer is most accurate for applications running Ember 2.x and above. –  Jun 29 '17 at 13:10
2

From the Updated Ember Documentation :

import { inject } from '@ember/controller';
export default Ember.Controller.extend({
  appController: inject('application')
});

For further reference, you can find out by this link https://guides.emberjs.com/release/applications/dependency-injection/#toc_ad-hoc-injections

Rakchamp25
  • 31
  • 3