Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Dependencies Between Modules

I'm facing a problem using Dependency Injection between modules. I have a module that implements a directive I need to use in other applications.

I added the dependency from this module in another app declaration like this:

angular.module('mainApp', ['ngRoute', 'directiveApp']);

However, the methods implemented into directiveApp.controller, doesn't seem to be visible from a page of MainApp, since the directive can't run a method it needs from their controller.

I know it's a little confusing, so I put an example in this plunker, that shows the problem I'm facing.

like image 884
Alex Gouvêa Vasconcelos Avatar asked Sep 28 '26 18:09

Alex Gouvêa Vasconcelos


1 Answers

When you inject another module into your own, the controllers and directives it implements become available, but you need to use them properly.

The way you are trying to do is not possible, you can do something like this: http://plnkr.co/edit/peHH226vxtkI48RFZ3Eq?p=preview

  <body ng-controller="MainCtrl">
    <h1>Value: {{name}}!</h1>
    <button ng-click="mainModule()">Call a function in the main module!</button>

    <div ng-controller="SubCtrl">
      {{name}}
      <button ng-click="dependentModule()">Call a function in the dependent module!</button>
    </div>
  </body>

But notice that you have two different $scopes and consequently two different name variables.

That means your dependentModule() function belongs to your SubCtrl and you can only use it inside its own $scope


That's not recommended, but if you really need to, you can use the other controllers on your own methods and then copy the results:

http://plnkr.co/edit/ranK9n08NNVuSKIGX15G?p=preview

main.controller("MainCtrl", function($scope, $controller) {


  $scope.name = "Initial value";
  $scope.mainModule = function() {
    $scope.name = "a function in the same module";
  };

  $scope.bridgeFunction = function(){
    // Create a new scope
    var injectedScope = $scope.$new();

    // Use it on the other controller
    $controller('SubCtrl',{$scope : injectedScope });

    // Call the methdo on the controller
    testCtrl1ViewModel.dependentModule(); //And call the method on the newScope.

    // Copy the result from that scope into your own
    $scope.name = testCtrl1ViewModel.name;
  }

});

A third option is to merge the two scopes, although this can get very messy, it is possible:

http://plnkr.co/edit/1NKStMuYy0e00dhuWKUD?p=preview

main.controller("MainCtrl", function($scope, $controller) {

  $scope.name = "Initial value";

  //This can get very messy, but it is possible to merge the two scopes:
  $controller('SubCtrl',{$scope : $scope });

  $scope.mainModule = function() {
    $scope.name = "a function in the same module";
  };

});

Hope that helps

like image 96
Fedaykin Avatar answered Oct 02 '26 01:10

Fedaykin