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

1

2 Answers 2

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();
            }
        ]);
})();
Sign up to request clarification or add additional context in comments.

2 Comments

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
sorry, i am unaware of angular testing :(
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;

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.