Prometheus
Prometheus

Reputation: 33655

Calling a function from controller1 within controller2 in angularjs

I have a controller that updates my awards scope:

Controller 1

.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
    function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {


        $scope.updateAwardScope = function () {
            resource = TokenRestangular.all('award');
            resource.getList()
                .then(function (awards) {
                    $scope.awards = awards;

                })
        }

    }])

Controller 2

I have another controller 2 with a click event thats outside of this controllers scope. Is it possible for the controller below to call the $scope.updateAwardScope function from controller 1?

.controller('MainController', function ($rootScope, $scope) {

 $scope.updateAwardScopeClick = function () {
    // somehow call function from controller 1 

  }


});

Upvotes: 0

Views: 104

Answers (2)

Sandeep Shabd
Sandeep Shabd

Reputation: 721

You can use angular broadcast and receive

Controller1

    .controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {


    $scope.updateAwardScope = function () {
        resource = TokenRestangular.all('award');
        resource.getList()
            .then(function (awards) {
                $scope.awards = awards;
                $rootScope.broadcast("update.awards");

            })
    }

}])

Controller 2

    .controller('MainController', function ($rootScope, $scope) {

     $rootScope.$on('update.awards', function(){
        $scope.updateAwardScopeClick();
     });

       $scope.updateAwardScopeClick = function () {
         // somehow call function from controller 1 

         }
       });

Upvotes: 1

Gus
Gus

Reputation: 76

I've found the use of the factory/service pattern to be a very effective way of reusing code in angular applications. For this particular case you could create an AwardFactory, inject it in your controllers and then call the update function. i.e

AwardFactory

myApp.factory('AwardFactory', ['TokenRestangular', function(TokenRestangular.all) {
  var factory = {
    awards: []
  };

  factory.update = function() {
    resource = TokenRestangular.all('award');

    resource.getList().then(function (awards) {
      factory.awards = awards;
    });

    return factory.awards; // You can skip the return if you'd like that
  };

  return factory;
}]);

YourController

.controller('MainController', function ($rootScope, $scope, AwardFactory) {

 $scope.updateAwardScopeClick = function () { 
   AwardFactory.update();
 }
});

Hope it helps!

Upvotes: 1

Related Questions