Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Inject controller inside another controller from the same module

Is possible to inject a controller into another controller that is part of the same module?

example:

var app = angular.module('myAppModule', [])
.controller('controllerOne', ['$scope', function($scope){
  $scope.helloWorld = function(){
    return 'Hello World';
  }
}])
.controller('controllerTwo', ['$scope', 'controllerOne', function($scope, controllerOne){
  console.log(controllerOne.helloWorld());
}])

I keep getting unknown provider on controllerOne. I don't see how that's possible since they coexist in the same module. Any help would be much appreciated.

like image 460
Joseph Freeman Avatar asked Apr 28 '15 18:04

Joseph Freeman


2 Answers

You need to use $controller dependency by using that you can inject one controller to another

.controller('controllerTwo', ['$scope', '$controller', function($scope, $controller){
  $controller('controllerOne', {$scope: $scope})
  //inside scope you the controllerOne scope will available
}]);

But do prefer service/factory to share data

like image 103
Pankaj Parkar Avatar answered Sep 29 '22 04:09

Pankaj Parkar


Move your logic into a "service" (either a factory/service/provider). I personally prefer factories, I just like controlling my own object instead of using this or anything like that with the other options.

Using a service, you give yourself the ability to abstract business logic from your controllers, and make that logic -- reusable -- !

var app = angular.module('myAppModule', [])

// typically people use the word Service at the end of the name 
// even if it's a factory (it's all the same thing really...

.factory('sharedService', function () {

    var methods = {};

    methods.helloWorld = function () {
        return 'Hello World!';
    };

    // whatever methods/properties you have within this methods object
    // will be available to be called anywhere sharedService is injected.

    return methods;
})

Notice sharedService is injected

.controller('ControllerOne', ['$scope', 'sharedService', function($scope, sharedService) {
    $scope.helloWorld = sharedService.helloWorld();
}])

// Notice sharedService is injected here as well
.controller('ControllerTwo', ['$scope', 'sharedService', function($scope, sharedService){

    // Now we can access it here too!
    console.log( sharedService.helloWorld() );
}]);

Side note : Controllers should be capitalized to show their significance!

The power of services :)

like image 30
Mark Pieszak - Trilon.io Avatar answered Sep 29 '22 06:09

Mark Pieszak - Trilon.io