0

I have a directive which is associated with one controller and the functions in my controller defined as

   MyFormController.prototype.addNewRow = function addNewRow() {
             //Adding row code
};

I want to call this method from another controller, possible ways?

I ve user the service and moved the code into that service which is shared across the controllers, however the service code does the DOM manipulation, and then i guess the next question would be that can we use $compile in a service test case

vaibhav
  • 3,929
  • 8
  • 45
  • 81
  • possible duplicate of [What's the correct way to communicate between controllers in AngularJS?](http://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs) – Shashank Agrawal Apr 25 '15 at 08:38

2 Answers2

2

service or factory is used to share data between controller.so it would be best to define function in service and factory.

demo:

(function() {
    angular.module('app', [])
        .service('svc', function() {
            var svc = {};

            svc.method = function() {
                alert(1);
            }

            return svc;
        })
        .controller('ctrl', [
            '$scope', 'svc', function($scope, svc) {
                svc.method();
            }
        ]);
})();
Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79
  • I ve user the service and moved the code into that service which is shared across the controllers, however the service code does the DOM manipulation, and then i guess the next question would be that can we use $compile in a service test case – vaibhav Apr 25 '15 at 09:43
  • sorry, i am unaware of angular testing :( – Mukund Kumar Apr 25 '15 at 09:48
0

You should not!!!

That defeats the whole purpose of modularity. If possible try to make the function generic and create a service/factory. Now both the places where you need, use the same generic function defined in service and do their stuff.

Otherwise you can also look at events to make changes accordingly. Look at this blog post: http://ilikekillnerds.com/2014/11/angularjs-call-controller-another-controller/

Last but the worst solution is (avoid using this, this is literally an aweful way) is catching the element inside directive and getting its scope and taking the function from it. Example,

var otherControllerFunc = $(".inside-directive").scope().yourfunc;
Kop4lyf
  • 4,520
  • 1
  • 25
  • 31
  • I ve user the service and moved the code into that service which is shared across the controllers, however the service code does the DOM manipulation, and then i guess the next question would be that can we use $compile in a service test case – vaibhav Apr 25 '15 at 09:43