Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a controllers method in another controller Ember

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?

like image 727
mohsinali1317 Avatar asked Apr 04 '14 11:04

mohsinali1317


People also ask

Can we call controller method from another controller?

Yes, you can call a method of another controller. The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.

What is controller in Ember JS?

In Ember. js, controllers allow you to decorate your models with display logic. In general, your models will have properties that are saved to the server, while controllers will have properties that your app does not need to save to the server.


2 Answers

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);
like image 121
GJK Avatar answered Sep 21 '22 23:09

GJK


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

like image 21
Ziyad Al Obaidi Avatar answered Sep 21 '22 23:09

Ziyad Al Obaidi