Using “require” in Directive to require a parent Controller

前端 未结 2 1825
执念已碎
执念已碎 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 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 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.

    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.

提交回复
热议问题