Using “require” in Directive to require a parent Controller

前端 未结 2 1826
执念已碎
执念已碎 2020-12-06 11:10

I try to \"require\" a parent controller (not directive) but AngularJS returns an exception. The code is like this:

JS

app.controller(\"myControlle         


        
相关标签:
2条回答
  • 2020-12-06 11:55

    Require is of using other directives controllers in another directive , please refer the below example

    var App =  angular.module('myApp',[]);
    
    //one directive
    
    App.directive('oneDirective',function(){
    
      return {
          restrict: 'E',
          controller:function($scope){
    
           $scope.myName= function(){
                console.log('myname');
              }
    
             }
        }
    
    });
    
       //two directive
    
      App.directive('twoDirective',function(){
    
      return {
          require:'oneDirective' //one directive used,
          link : function(scope,ele,attrs,oneCtrl){
             console.log(oneCtrl.myName())
         }
    
       }
    
      })
    
    0 讨论(0)
  • 2020-12-06 12:02

    Notation require: "^myController" means that your directive will try to access another directive called myController and defined on some of the ancestor tags as my-controller attribute or <my-controller> tag. In your case you don't have such directive, hence the exception.

    This is not very conventional what you are trying to do, but if you really want to require outer controller in your directive you can require ngController:

    app.directive("myDirective", function($q) {
        return {
            require: "^ngController",
            template: "",
            link: function(scope, element, attrs, myCtrl) {
                // ...
                console.log(myCtrl);
            }
        };
    });
    

    However, this is not very good idea. I can't imagine why you might need it like this. I would recommend to look into scope configuration properties and how you can pass executable function references into your directive from outer controller.

    <div my-directive some-callback="test()"></div>
    

    and in directive define scope:

    scope: {
        someCallback: '&'
    }
    

    where in controller you would have $scope.test = function() {};. Then you would not need to require controller explicitly in directive.

    0 讨论(0)
提交回复
热议问题