1

How can I call function loadTable from another controller?

    app.controller('tableCtrl', ['$scope', function (scope) {
       scope.loadTable = function() {
       //some code
       };
    });

    app.controller('secondCtrl', ['$scope', function (scope) {
       scope.buttonClick = function() {
       //call loadTable from tableCtrl
       };
    });
Václav Pavlíček
  • 419
  • 2
  • 9
  • 21
  • 1
    Duplicate of http://stackoverflow.com/questions/19468334/call-a-method-of-a-controller-from-another-controller-using-scope-in-angularjs – djangonaut Mar 19 '15 at 14:14
  • try with $rootScope and for more try to go through tutorial for $rootScope. – Naitik Mar 19 '15 at 14:16

2 Answers2

3

Try $emit-$on(publish-subscribe) mechanism.

app.controller('tableCtrl', ['$scope', function (scope) {
    scope.loadTable = function() {
        //some code
    };

    $rootScope.$on('load-table', function (event, arg1, arg2) {
        // now trigger the method.
        scope.loadTable();
    });
});

app.controller('secondCtrl', ['$scope', function (scope) {
    scope.buttonClick = function() {
        //call loadTable from tableCtrl
        //emit the event
        $rootScope.$emit('load-table', 'arg1', 'arg2');
    };
});
Vinay K
  • 5,562
  • 1
  • 18
  • 27
1

You should perhaps use a service such as

app.factory('tableService', [function () {

   return {
       loadTable : function() {
          //some code
       }
   };
});


app.controller('tableCtrl', ['$scope', 'tableService', function (scope, tableService) {

});

app.controller('secondCtrl', ['$scope', 'tableService', function (scope, tableService) {
   scope.buttonClick = function() {
       tableService.loadTable();
   };
});

Your tableCtrl would then need to save any data using another function on the service.

APD
  • 1,459
  • 1
  • 13
  • 19