1
unified.controller('YourteamController', function uniYourteamController($scope) {    
    testController.listTeams();
});    

unified.controller('testController', function testController($scope) {
    $scope.listTeams = function() {
        //Listing process
    };    
});

I have two controller. I need to call a function(listTeams()) in another controller(testController). How to call this using angularjs

Naveen
  • 757
  • 3
  • 17
  • 41

5 Answers5

1

Go the service way. Easier to test, and more in line with 'best practices'.

angular.module('sharedService', function () {
  function listTeams () {
    return 'teams!';
  }

  angular.extend(this, {
    listTeams: listTeams
  })
});

angular.module('ctrl1', function ($scope, sharedService) {
  angular.extend($scope, {
    listTeams: sharedService.listTeams
  });
});

angular.module('ctrl2', function ($scope, sharedService) {
  angular.extend($scope, {
    listTeams: sharedService.listTeams
  });
});
0

You need to inject first controller as dependency to second controller. Here is how to do it.

Community
  • 1
  • 1
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
0

do the following ...

  unified.controller('YourteamController', function uniYourteamController($scope) {    
        var testController= $scope.$new();
        $controller('testController',{$scope : testCtrl1ViewModel });
        testController.listTeams();
    });    

    unified.controller('testController', function($scope) {
        $scope.listTeams = function() {
            //Listing process
        };    
    });
ngLover
  • 4,439
  • 3
  • 20
  • 42
0

you have to make a service that will return a function that can be used in both controllers having diffrent scope.

========================================

unified.controller('YourteamController', function uniYourteamController($scope, $abc) {

$abc.listTeams();
});

unified.controller('testController', function testController($scope, $abc) {
$abc.listTeams();
});

unified.service('abc', function () {


this.listitems = function () {

}
});
pankaj malik
  • 107
  • 2
  • 15
0

Just try this

unified.controller('YourteamController', function uniYourteamController($scope) {    
    $scope.$parent.listTeams();
}); 
Saiju
  • 350
  • 2
  • 8