How can I use a registered controller in my angular directive?

后端 未结 2 1272
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 11:56

I have a controller registered like this:

myModule.controller(\'MyController\', function ($scope, ...some dependencies...)
{
    ....

Using

相关标签:
2条回答
  • 2021-01-11 12:17

    It appears that you can just use:

    controller: 'MyController' 
    

    IF the controller is in the same module as the directive or a higher level module composed of the module with the directive in it.

    When I tried it with two different modules composed into an app module (one for the controller and one for the directive), that did not work.

    0 讨论(0)
  • 2021-01-11 12:29

    The answer you've already accepted works, and in almost all cases should be chosen...

    For sake of completeness: Here is how you can use a controller from another module

    (PS: Don't do this. lol :P)

    var app = angular.module('myApp', ['myDirectives']);
    
    app.controller('AppCtrl1', function($scope) {
        $scope.foo = 'bar';
    });
    
    
    var directives = angular.module('myDirectives', []);
    
    directives.directive('test', function($controller) {
       return {
           template: '<h1>{{foo}}</h1>',
           link: function(scope, elem, attrs) {
              var controller = $controller('AppCtrl1', { $scope: scope });
    
              console.log($scope.foo); //bar
           }
       };
    });
    
    0 讨论(0)
提交回复
热议问题