2
    angular.module('starter.controllers', [])
    .controller('controller1',function($scope) {
    $scope.function1= function () {
    ---------------
    })
    .controller('controller2',function($scope) {
    $scope.function1= function () {
    //is it possible to access method form controller1 in controller2 like this
controller1.function();
    })

I'm beginner in angular JS please guide me to complete my code.

1
  • 3
    no you cannot access that in second controller but if you want something like this to share function b/w controllers create a angular service . Commented Jan 27, 2015 at 7:48

1 Answer 1

2

In AngularJS you use Services for that kind of things.

Just create a Service with the Function you want to use multiple times:

.service('myService', function() {
    return function() {
        //your function1
    };
})

Then you use this Service as dependency:

.controller('controller2', [
    '$scope',
    'myService',//say you want the service as second param
    function($scope, myService) {
        $scope.function1 = function() {
            myService();//your function is here
        };
    }
])

And the same in the other controller:

.controller('controller1', [
    '$scope',
    'myService',
    function($scope,myService) {
        $scope.function1 = myService;//bind the service to the scope
    }
])
Sign up to request clarification or add additional context in comments.

2 Comments

Moreover, if you need a service with multiple functions just return an object with function variables and call them like myService.niceFunction() from anywhere.
@DonJuwe of course, if he uses the other function also somewhere else, than it is smarter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.