Naveen
Naveen

Reputation: 777

How to call a function in another controller in angularjs

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

Upvotes: 1

Views: 151

Answers (5)

Saiju
Saiju

Reputation: 350

Just try this

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

Upvotes: 0

pankaj malik
pankaj malik

Reputation: 107

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 () {

}
});

Upvotes: 0

user1364910
user1364910

Reputation:

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
  });
});

Upvotes: 1

ngLover
ngLover

Reputation: 4578

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
        };    
    });

Upvotes: 0

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

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

Upvotes: 0

Related Questions