1

template

<section id="content" ng-controller="ReservationController as resvnCtrl" >            
        <form role="form" name="resvnCtrl.form">    
            <div  data-date-picker>
            </div>    
        </form>
    </section>

directive

var eateryDirectives=angular.module('eateryDirectives',['eateryControllers']);

     eateryDirectives
           .directive('datePicker',function(){
               var directive={
                   require:'^resvnCtrl',
                   link:function(scope,ele,attrs,cntrl){
                       console.log(cntrl);
                   }
               };
                return directive;
            });

I got controller could not find error. By the way controller and diretcive are in different modules. Does that matter? How to access that controller from directive?

lch
  • 4,569
  • 13
  • 42
  • 75
  • ReservationController is in eateryControllers module – lch Oct 16 '15 at 02:28
  • It's hard to say how you should do this without knowing more about what your overall goal is, but your problem is that you're trying to use the directive's `require` in a way that it can't be used. http://stackoverflow.com/questions/15672709/how-to-require-a-controller-in-an-angularjs-directive – m59 Oct 16 '15 at 02:30
  • i did the same what was explained in that link – lch Oct 16 '15 at 02:33
  • 1
    No, you have `ng-controller` applying a controller to some html and a directive trying to require that controller. That isn't how it works. The directive's `require` tries to find another **directive** that has that controller. – m59 Oct 16 '15 at 02:41
  • @m59 Actually there is no problem with requiring controller directive, it's just a directive after all. Of course, it doesn't scale, but it's totally possible. See my answer. – dfsq Oct 16 '15 at 05:38

1 Answers1

2

If you want to require controller then you should require ngController directive. Yes, you can do it, it's just normal directive after all:

require: '^ngController'

However, don't do this, this is totally wrong approach. If you want some data from this controller or methods, you should use scope config and pass necessary fields into isolated scope:

eateryDirectives.directive('datePicker', function () {
    var directive = {
        scope: {
            data: "=",
            onSelect: "&"
        },
        link: function (scope, ele, attrs, cntrl) {
            console.log(cntrl);
        }
    };
    return directive;
});

and in HTML:

<section id="content" ng-controller="ReservationController as resvnCtrl" >            
    <form role="form" name="resvnCtrl.form">    
        <div data-date-picker data="resvnCtrl.dates" on-select="resvnCtrl.update()"></div>    
    </form>
</section>
dfsq
  • 191,768
  • 25
  • 236
  • 258